FAQ Database Discussion Community


Injecting an instance using Unity whose constructor parameter is not known

design-patterns,dependency-injection,unity,constructor-injection
I have an interface as follows public interface IDataProvider { List<string> GetData(); } Implementation of it public class TextDataProvider: IDataProvider { public TexDataProvider(string source){...} public List<string> GetData() {...} } One of my services uses IDataProvider to get data. Different implementations could be injected by changing the Unity Register method with...

Prism Event Aggregators and WCF Services and Unity

c#,wcf,unity,prism
I am using prism event aggregators to trigger and associate events (publish and subscribe). The service is only instantiated if there is a request for it. Either from a client (through a channel) or from another service (as a class object). Issue: If an event is not subscribed (registration and...

Using Unity DI container in WPF application

c#,wpf,unity
I'm new in WPF, and consider to try DI. I decide to take OnStartup method as Composition Root. protected override void OnStartup(StartupEventArgs e) { IUnityContainer container = new UnityContainer(); container.RegisterType<IMailSender, Model.Concrete.GmailSender>(); var mainWindow = container.Resolve<MainWindow>(); mainWindow.Show(); } But, after the application is started, appears two windows, normal, with my content,...

Dependency Injection in multilayered Application

c#,wpf,mvvm,dependency-injection,unity
So my problem is the following. My solution contains the following projects (with references): Presentation Layer, contains Views (has a reference to Application Layer) Application Layer, contains ViewModels (has a reference to Domain and Persistence Layer) Domain Layer, contains all Models (no reference to anything) Persistence Layer, stores data with...

Unity Property Injection on AuthorizeAttribute

c#,asp.net-mvc,authentication,dependency-injection,unity
I am trying to inject a dependancy into a custom AuthorizeAttribute as follows: public class UserCanAccessArea : AuthorizeAttribute { readonly IPermissionService permissionService; public UserCanAccessArea() : this(DependencyResolver.Current.GetService<IPermissionService>()) { } public UserCanAccessArea(IPermissionService permissionService) { this.permissionService = permissionService; } protected override bool AuthorizeCore(HttpContextBase httpContext) { string AreaID = httpContext.Request.RequestContext.RouteData.Values["AreaID"] as...

what are pitfalls of making UnityContainer not thread safe?

c#,dependency-injection,unity
I am adding dependency injection to my library and I use Unity for that. And I am wondering if I need to take some additional steps to make Unity Container thread-safe. I found couple of articles that are talking about Thread-safe container (example: http://www.fascinatedwithsoftware.com/blog/post/2012/01/04/A-Thread-Safe-Global-Unity-Container.aspx ) but I don't understand if...

Unable to inject with unity a complex type to web api 2

c#,asp.net-web-api,dependency-injection,unity,asp.net-web-api2
I have a complex type to inject into a webapi controller and I am unable to resolve this dependency public class MyController(IMyComplexType) The implementation of IMyComplexType has at least 5 dependencies I1, ... I5(so its implementation recieve I1...I5) I have a Bootstrapper class to Register all dependencies, below a snippet...

How to dynamically inject service into asp.net web api controller based on http request parameter using Unity

c#,asp.net,asp.net-web-api,unity
I am using Unity to inject an instance of a service into the constructor of my ASP.NET Web API controller. In the below code, I want to inject a different implementation of IAuthenticationService based on the http request made. Is this possible? public class AuthenticateController : ApiController { public AuthenticateController(IAuthenticationService...

Is HierarchicalLifetimeManager the correct lifetime manager to use for WCF client / ChannelFactory

wcf,dependency-injection,inversion-of-control,unity,object-lifetime
I have a very simple WPF application that is calling There is one container for the application, that is configured when the application starts. The WPF app has a service reference to my WCF service. I have registered my generated proxy to the container like this: container.RegisterType<IAccountService>( new HierarchicalLifetimeManager(), new...

Unity ResolveAll not working

c#,dependency-injection,inversion-of-control,unity
I am using Unity for the first time. I am trying to add some dependencies in code, but they are not getting resolved. Code below: public interface IClassA { void Show(); void ShowCount(); int ID { get; set; } } class ClassA : IClassA { public int count = 0;...

Handling a dependancy from different project in a console application

c#,dependency-injection,unity
I have the following project structure in my solution: Project.Repository (Class Library) Project.Core (Class Library) Project.Web (MVC5 web front end) Project.Scheduler (Console Application) I am using Unity to handle my DI. My problem I have a method which sits in the Core layer, this method has a dependency on an...

WebAPI/Unity Intercept Request and Change ConectionString Unity Container for EF Context

entity-framework,asp.net-web-api,unity
I'm building an API that needs to connect to a different database per request. Currently I'm using EF. These databases all have the same schema, therefore I can share a DbContext class. I have repositories to abstract persistence, and these are the ones using the DbContext objects. Unity is handling...

C#, Unity IoC: Registering and resolving generic interfaces, good practices

c#,generics,architecture,unity
I wrote generic interface and over time, I started using it quite often. I had also idea to actually provide another generic interface, extending existing one. Now, when I look into my Unity config (IoC framework is irrelevant here), it looks like this: container.RegisterType<IConfigProvider<ICountryConfig>, CountryConfigProvider>(); container.RegisterType<IConfigProvider<ILanguageConfig>, LanguageConfigProvider>(); // IEnumerableConfigProvider<T> :...

Can I configure Unity to automatically return a fake for interfaces that are not registered?

c#,unit-testing,dependency-injection,mocking,unity
I'm a bit tired of manually registering fake dependencies in my unit tests... I'm wondering if there is a way to configure Unity in such a way that, if there is no registered implementation for a given type, it automatically creates a fake using FakeItEasy or some other mocking framework....

How to resolve dependency in static class with Unity?

c#,unity,extension-methods
I have the following extension method, which exists (naturally) in a static class. public static class MyExtensions { [Dependency] private static IMyDataContext _myDataContext { get; set; } public static void MyExtensionMethod(this MyType myType) { // do stuff _myDataContext.DoAwesomeThing(); } } the _myDataContext object is null. Normally I'd use the UnityContainer...

Unity registration fails after iisreset

dependency-injection,unity,web-api
I am registering a load of dependencies like so. container.RegisterTypes(AllClasses.FromLoadedAssemblies(), WithMappings.FromMatchingInterface, WithName.Default, overwriteExistingMappings: true); This registers things fine and the web api endpoints are properly configured. If I do iisreset or simply wait for a bit then things fail with The error message is not terribly helpful "exceptionMessage": "An error...

Unity resolving generic event handlers

c#,generics,unity,dependency-resolver
I'm using Unity to register all my domain event handlers like such : public static void RegisterTypes(IUnityContainer container) { container.RegisterType<IDomainEventHandler<ProductCreated>, ProductCreatedHandler>(new PerRequestLifetimeManager()); } My handler looks like this : public class ProductCreatedHandler : IDomainEventHandler<ProductCreated> { public void Handle(ProductCreated domainEvent) { // Handle the event } } My domain event looks...

'AutoMapper.Configuration' is a 'namespace' but is used like a 'type'

unity,automapper,ioc-container,automapper-3
I am trying to upgrade AutoMapper 1.1 to AutoMapper 3.3. I have the following statement in my current code that does not work in v3.3 container.RegisterType<IConfiguration, global::AutoMapper.Configuration>(new ContainerControlledLifetimeManager()); container is a Unity container. I am getting the following error. 'AutoMapper.Configuration' is a 'namespace' but is used like a 'type' How...

Using Unity.WebForms in ASP.NET

dependency-injection,webforms,unity
I am trying to implement DI in a webforms project, so I installed the Unity.WebForms dlls in my UI layer. As soon as I did an App_Start folder was created for me with a UnityWebFormsStart class file. Inside this file there is a method RegisterDependencies which asks to be edited....

Injecting UnitOfWork with dependency on HttpContext.Current

c#,asp.net-mvc,dependency-injection,unity,unit-of-work
I'm trying to inject a new UnitOfWork instance into my controllers with every new request. For that, I'm using the following code: container.RegisterType<HttpContextBase>(new InjectionFactory(c => new HttpContextWrapper(HttpContext.Current))); container.RegisterType<IEntitiesUnitOfWork, UnitOfWork>(new PerRequestLifetimeManager(), new InjectionConstructor( new Func<Entities>(() => new Entities()), new InjectionParameter<User>(UserProvider.AuthenticationData.User))); The User property in my...

Unity IoC with Windows Froms

c#,winforms,unity,ioc-container
So i have such an program architecture (LibraryManager): Data Access Layer has class, that has to manage data and communicate with the presenter public interface ILibraryDataManager { //some code... } public class LibraryDataManager:ILibraryDataManager { //some code... } Implementation of a primitive, do not dwell on the attention ... Next, in...

Entity Framework Code First can't find database in server explorer

c#,database,unity
So I was following this introduction to the Entity Framework Code First to create a new database ( https://msdn.microsoft.com/en-us/data/jj193542 ) and I followed the example completely. Now I want to add it to my server explorer in Visual Studio 2013. Tried both LocalDb ((localdb)\v11.0) or SQL Express (.\SQLEXPRESS) but the...

Get class type during dependency resoluton

c#,dependency-injection,unity,constructor-injection
When registering a type for my unity container, I need to pass in the calling class's type into the constructor of the resolved object. This is the class where I am injecting some interfaces into the constructor. namespace MyNamespace { internal class ProcessingService: IProcessingService { private readonly ISomeClass1 someClass1; private...

Dependency Injection using Unity in ASP.NET

c#,asp.net,dependency-injection,unity
I have a pretty straight forward setup. namespace ObjectNamespace { public class CustomProcessor : ICustomProcessor<myObject> { public CustomProcessorResult Execute(myObject Data) { try { var container = new UnityContainer(); // UnityConfigurationSection section = new UnityConfigurationSection(); var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); // this gives Microsoft.Practices.Unity.Configuration.UnityConfigurationSection section.Containers.Default.Configure(container); var configuration =...

Visual studio mistakes valid code as invalid after debug edit

c#,visual-studio,unity
I am using visual studio 2013 with unity 3.5 downloaded using nuget. I have Container class that looks like the following public class Container { static IUnityContainer _container; //<- System IDisposable error on _container static ILogger _logger = GetLogger(); //continuation here } My problem is when I execute the application,...

What is a good pattern for using multiple strategies one after another that is also extensible

c#,dependency-injection,unity,ioc-container,factory
I have a class that needs to get some data to perform analysis. Let's say the interface for getting the data is as follows: public interface IDataFetcher { List<someobject> GetData(); } In a very simple case my class will use this interface as follows in one of its methods: void...

is there a way to register a factory in Unity's XML configuration?

c#,.net,design-patterns,unity
Is there a way to register a factory in Unity's XML configuration? Unity should inject some constructor parameters and use the factory in order to instantiate the object. Here is a Spring .NET based example: <object id="name" type="Namespace.Factory, Assembly" factory-method="Create"> <constructor-arg name="intParam" value="1" /> <constructor-arg name="objParam" ref="objectName" /> </object> Many...

Abstract Factory fit into Unity

c#,dependency-injection,unity,abstract-factory
We are building an application which has a number integration touch points with other systems. We are effectively using Unity for all our dependency injection needs. The whole business layer has been built with an interface driven approach, with the actual implementation being injected at an outer composition root during...

Manually dispose OWIN WebApp

c#,asp.net-web-api,unity,asp.net-web-api2,owin
I'm trying to use OWIN to Self-Host Web API while running my tests and I want to start it in BeforeEach and stop in AfterEach methods. All examples, that I found suggests to use using keyword, e.g. using (WebApp.Start<Startup>(url: baseAddress)) { ... } But in my case it doesn't help....

AccountController in MVC 5 and Unity IoC

c#,asp.net-mvc-5,unity
I have created a new ASP.NET MVC 5 project with Individual User Authentication in place. I have then gone ahead and installed Unity IoC as a package and configured that by doing the following inside UnityConfig.cs: public static void RegisterTypes(IUnityContainer container) { container.RegisterTypes(AllClasses.FromLoadedAssemblies(), WithMappings.FromMatchingInterface, WithName.Default); container.RegisterType<AccountController>(new InjectionConstructor()); } From stuff...

Unity RegisterTypes with Assembly wildcard

c#,.net,unity
Is it possible to use an assembly wild card when calling container.RegisterTypes? i.e. If I want to just register classes from Assemblies that start with Foo.Bar, is there a way to do that. So if I had Foo.Bar.Test1 and then Foo.Bar.Test2 assemblies, it would grab both of those without having...

Why registering a generic type with one type parameter to Unity Container fails here?

c#,.net,generics,unity,enterprise-library
I am trying to register a generic type to unitycontainer via configuration file, as shown below in a simplified way. However on the LoadConfiguration method call I get an error: "The type name or alias IDataLoader`1[Bar] could not be resolved. Please check your configuration file and verify this type name."...

Unity.Mvc3 vs Unity.Mvc

asp.net-mvc,asp.net-mvc-3,unity
Using the Unity.Mvc3 with a Mvc 3 application, i could register my IDummyService as follows: container.RegisterType<IDummyService, DummyService>(new HierarchicalLifetimeManager()); On each web request, a new instance of my IDummyService is created (as explained in this article), but since I upgraded Mvc 3 to Mvc 4 and hense Unity.Mvc3 to Unity.Mvc, an...

Inject value at runtime

c#,asp.net-web-api,unity
I have repository classes that require runtime values taken from Thread.CurrentPrincipal (i.e. authorization claims) in combination with regular singleton classes. Given public class MyRepository : IMyRepository { private readonly DependencyClass _dependency; private readonly string claim; protected MyRepository(DependencyClass _dependency, string claim) { //... When registering the repository, how can the claim...

Unity - Register Generic Type With Interface Parameters

c#,generics,unity
I am attempting to implement CQRS by following this article, I have got everything working but I cannot work out how to register all of the IQueryHandler types in Unity. I have the following classes: // query public class GetTitleByIdQuery : IQuery { public int Id { get; set; }...

Why does Unity RegisterType not re-register mappings correctly

.net,dependency-injection,unity
I need to register many Type mappings but for just a few I need to re-register using different dependecy injected Properties. With Unity this appears impossible and it seems to be a bug with RegisterType<TFrom, TTo>() Here is a unit test to demonstrate that the 2nd call does not clear...

Dependency injection with unity in a class library project

c#,.net,asp.net-mvc,dependency-injection,unity
I am new with dependency injection pattern. That's why little confused about few things. Scenario: I have a class library project called 'MailCore'. This project has interface and classes that perform all email sending stuff. I have a mvc project 'The site'. It uses the 'MailCore' project to send email....

error: Make sure that the controller has a parameterless public constructor webapi

asp.net-mvc,parameters,controller,unity,asp.net-web-api2
I am using webapi, unity, and mvc. I am getting the error "Make sure that the controller has a parameterless public constructor". I have seen treads on similar problems but still can't get it to work. I have installed unity.webapi and seem to have all the necessary references: Microsoft.Practices.Unity -...

Unity: The type name or alias x could not be resolved. Please check your configuration file and verify this type name

c#,.net,dependency-injection,unity
Error code : The type name or alias UnitOfWorkFactory could not be resolved. Please check your configuration file and verify this type name. I'm scraping google results / trying to debug for 2 days now, and I didn't find any solution yet. Mention that "ApplicationService" is being resolved. I verified...

Is there a way to inject List in a constructor using the Bootstrap file and Unity Container?

c#,generics,dependency-injection,unity
I am working on Unity container to inject dependencies through a constructor , I was able to resolve all other types apart from the List of objects. I tried to register the type as container.RegisterType<IList<TypeA>,List<TypeA>>(); in the Bootstrap.cs file. When I try to resolve the type , I am getting...

How to access nested Unity Dependency Injection created objects?

c#,asp.net-mvc,dependency-injection,unity
This is a beginner question for Unity so forgive me. In my Unity Config I have the following that creates my database context (Entity Framework), Unit of Work, and a Repository pattern object (from reverse pocos and generic repo/uow): container .RegisterType<IDataContextAsync, myDbContext>( new PerRequestLifetimeManager(), new InjectionConstructor(new object[] { connString }))...

RabbitMQ with Unity IOC Container in .NET

.net,rabbitmq,unity
I am using Unity App Block as my IOC container for my service layer of a WCF project. This works quite well using the Unity.WCF library to plug it into each WCF service. I recently introduced RabbitMQ into my service layer and I am currently using the "using" blocks to...

Decorators in Unity with many arguments

c#,.net,asp.net-web-api,inversion-of-control,unity
I have the following problem. I have two classes T1 and T2 that both implement interface T. I'd like T2 to decorate T1 so when I create an instance of T T2 is called first, then T1. public class T1 : IT { public void Call() { Write("T1"); } }...

Property injection with Unity

c#-4.0,dependency-injection,unity
i encoutered problem with unity, i want to use property injection, here is what i had in my code : config of the container : public static void RegisterTypes(IUnityContainer container) { container.RegisterType<GTModelContainer, GTModelContainer>(new HttpContextLifetimeManager<GTModelContainer>()) .RegisterType<IUnitOfWork, UnitOfWorkGT>() .RegisterType<ILogger, Logger>(new ContainerControlledLifetimeManager()) .RegisterType<ISocieteServices, SocieteServices>() ; } SocieteService Class : public class...

The type X has multiple constructors of length 1. Unable to disambiguate

c#,asp.net,dependency-injection,unity
I'm working at a ASP.NET Webforms project and is using Unity for DI. This project also use DevExpress ASP.NET Ajax Controls. Now we have run into problem and it seems to be a conflict between DevExpress and Unity. This is the Unity configuration [assembly: WebActivator.PostApplicationStartMethod(typeof(Sales.Web.App_Start.UnityWebFormsStart), "PostStart")] namespace Sales.Web.App_Start { ///...

ObservableCollection loses its collection

c#,wpf,unity,prism,prism-5
Using WPF with Prism and Unity - I have a strange defect where an ObservableCollection is losing its collection. I’ve added a real backing field to see if there was something funny happening with the automatic property. I’ve added a CollectionChanged event handler on the field that only fires when...

Factory Object or Function, or Pass Unity Container?

c#,dependency-injection,unity,factory,factory-pattern
I have an object that provides a sequence value to various consumers. The provider must manage many sequences, because the consumers could ask to get a new value for any one of the ongoing sequences. All of the sequences follow the same pattern, but they are path dependent and thus...

Unity resolve using type from derived class

c#,inversion-of-control,unity
I am trying to setup a structure where I have two sets of derived classes (models and views) implementing a common interface, and I want to use Unity to allow me to create/resolve a view from a model instance. E.g., public interface ICommonA {} public class ModelA : ICommonA {}...

How can get access to Unity container in a class library ActionFilterAttribute?

c#,dependency-injection,unity,class-library,actionfilterattribute
So, I have a web project that utilizes Unity to inject UserRepository for interfaces IUserRepository. I have a class library which contains a custom ActionFilterAttribute. This custom attribute class is used on many actions already. I want to add some code to it to check for a value in the...