Unity and UnityContainer - c#

I have many projects :
Service.DataAccess
Service.DataAccess.Interfaces
Service.Main
Service.Factory
Service.DataAccess have a reference to Service.DataAccess.Interfaces.
Service.Main have a reference to Service.DataAccess.Interfaces and to Service.Factory
In Service.Main I have :
var instance = Service.Factory.ObjectFactory.Resolve<Service.DataAccess.Interfaces.IDataAccessLayer>();
In Service.Factory :
public void InitContainer(IUnityContainer container)
{
var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Configure(container); //Exception here!
}
In my configuration file :
<?xml version="1.0" encoding="utf-8" ?>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<container>
<register type="Service.DataAccess.Interfaces.IDataAccessLayer, Service.DataAccess.Interfaces"
mapTo="Service.DataAccess.DataAccessLayer, Service.DataAccess" />
</container>
</unity>
But I have a exception at runtime in InitContainer method :
The type name or alias Service.DataAccess.Interfaces.IDataAccessLayer could not be resolved. Please check your configuration file and verify this type name.
I don't understand
Thank's!

Your container need to be able to access the constructor of your implementation. So it needs access to a public constructor of the class Service.DataAccess.DataAccessLayer, which means that your Service.Factory needs to reference Service.DataAccess. But also Service.DataAccess.Interfaces, because otherwise it will not find the interface.
You may also separate it into several steps, and let each library take care of their own registrations.
Main doesn't necessarily need have a reference to Service.DataAccess if it goes through Service.Factory to create it. Let's take a very simple example.
In your Main:
var container = new UnityContainer();
container.Register<IFactory, SomeFactory>(); // Factory is a class in Service.Factory.
// Let your factory project take care of it's registrations as well.
Service.Factory.Startup.InitContainer(container);
var factory = container.Resolve<IFactory>();
Service.DataAccess.Interfaces.IDataInterface foo = factory.Create();
In your Service.Factory:
// Class for initiating registrations.
public static class Startup
{
public static InitContainer(IUnityContainer container)
{
var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Configure(container);
}
}
// Some example class...
public class SomeFactory : IFactory
{
private readonly IUnityContainer _container;
public SomeFactory(IUnityContainer container)
{
_container = container;
}
public IDataInterface Create()
{
// return the implementation.
return _container.Resolve<IDataInterface>();
}
}
Note that the SomeFactory uses the ServiceLocator anti-pattern. But it's mostly a proof-of-concept to show how it could work. It's a way to let Service.Main only reference the interfaces, but not the concrete classes. Service.Factory, however, needs to reference both.

Related

Dependency Injection Container - How to keep available to

When creating an application with Dependency Injection and it utilizes a framework for Dependency Injection such as Unity (or Ninject).
How do you initialize registering the interfaces to the container at the beginning all together and keep them available for the application to use throughout its running lifecycle of the application?
Do you need to pass the DI Container to each method that may utilize dependency injection, or is there some way to make the container globally accessible so that you can register them all together in the beginning and access them throughout running the application without having to continually pass them, and be able to utilize them when ever needed?
Environment: Visual Studio 2015, C#, Microsoft Unity (for DI Container)
Example Code
static void Main(string[] args)
{
// Make Unity resolve the interface, providing an instance
// of TrivialPursuit class
var diContainer = new UnityContainer();
diContainer.RegisterType<IGame, TrivialPursuit>();
var gameInstance = diContainer.Resolve<IGame>();
var xotherClass = new AnotherClass();
xotherClass.TestOtherClassOtherMethod();
}
------ Another class without context of the Dependency Injection Class ------
public void TestOtherClassOtherMethod()
{
IGame gameInstance = -- -Container is Not available to resolve from in this class ---
}
Reason: I don't want to need to pass every possible type that I may need later on to each class I load up, I will just want to use the instances when I need them. The more deeper I get into classes, later as the application becomes more complex, I won't want to pass down instances for each type up from the Main() method to each class.
A Dependency Injection (DI) container is just that. A framework for facilitating DI. You don't pass the container around in order to resolve instances of objects. You just request the type you need in your classes constructor and the DI framework will inject the appropriate dependency.
Mark Seemann has written a good book on dependency injection that I would recommend.
You register everything that'll need to be resolved with the container in the composition root. That is to say when your program starts up is when everything should be registered.
Let's say we have the following code:
public class MyClass
{
public Run()
{
var dependency = new Dependency1();
dependency.DoSomething();
}
}
public class Dependency1
{
public void DoSomething()
{
var dependency = new Dependency2();
dependeny.DoSomethingElse();
}
}
public class Dependency2
{
public void DoSomethingElse()
{
}
}
This gives us the above dependency chain: MyClass -> Dependency1 -> Dependency2.
The first thing we should do is refactor the classes to take their dependencies through their constructor and rely on interfaces rather than concretions. We can't inject dependencies unless there is a place to inject them (constructor, property, etc).
Here is the refactored code:
public interface IMyClass
{
void Run();
}
public interface IDependency1
{
void DoSomething();
}
public interface IDependency2
{
void DoSomethingElse();
}
public class MyClass : IMyClass
{
public readonly IDependency1 dep;
public MyClass(IDependency1 dep)
{
this.dep = dep;
}
public void Run()
{
this.dep.DoSomething();
}
}
public class Dependency1 : IDependency1
{
public readonly IDependency2 dep;
public MyClass(IDependency2 dep)
{
this.dep = dep;
}
public void DoSomething()
{
this.dep.DoSomethingElse();
}
}
public class Dependency2 : IDependency2
{
public void DoSomethingElse()
{
}
}
You'll notice the classes now all take their dependencies through their constructors and do not new up anything. Classes should only take in dependencies that they actually need. For example, MyClass does not NEED a Dependency2 so it doesn't ask for one. It only asks for a Dependency1 because that's all it needs. Dependency1 NEEDS Dependency2, not MyClass.
Now to wire it all up WITHOUT a container we would just new it all up in the composition root:
void Main()
{
var myClass = new MyClass(new Dependency1(new Dependency2()));
}
You can see how that could get cumbersom if we had tons of classes and depdencies. That's why we use a container. It handles all the depdency graph for us. With a container we'd rewrite it as follows:
void Main()
{
// the order of our registration does not matter.
var container = new Container();
container.Register<IDependency1>.For<Dependency1>();
container.Register<IDependency2>.For<Dependency2>();
container.Register<IMyClass>.For<MyClass>();
// then we request our first object like in the first example (MyClass);
var myClass = container.Resolve<IMyClass>();
myClass.Run();
}
In the second example the container will handle wiring up all the dependencies. So we never need to pass Depedency2 to MyClass and then to Depedency1. We only need to request it in Dependency1 and the container will wire it up for us like in the first example.
So in your example we would rewrite it like so:
static void Main(string[] args)
{
var game = new UnityContainer();
game.RegisterType<IGame, TrivialPursuit>();
game.RegisterType<IAnotherClass, AnotherClass>();
game.RegisterType<IYetAnotherClass, YetAnotherClass>();
var gameInstance = game.Resolve<IGame>();
// you'll need to perform some action on gameInstance now, like gameInstance.RunGame() or whatever.
}
public class Game : IGame
{
public Game(IAnotherClass anotherClass)
{
}
}
public class AnotherClass : IAnotherClass
{
public AnotherClass(IYetAnotherClass yetAnotherClass)
{
}
}
public class YetAnotherClass : IYetAnotherClass {}
In these cases there is no need to pass the container around. You register your dependencies with the container then request them in your classes constructors. If you wish to use the container in the class WITHOUT requesting it through the constructor then you are not doing DI you are just using the container as a singleton service locator. Something that should generally be avoided.
Container as a Service Locator
This should be generally avoided but if you want to use the container as a service locator you have two options:
1) Pass the container into your classes that need it through the constructor.
You can use the above examples for wiring your classes up for DI. But instead of requesting a dependency like IDependency in the constructor you just pass the container.
public class Game : IGame
{
public Game(IContainer container)
{
var blah = container.Resolve<IBlah>();
}
}
2) Request your container through a static class:
public static class ServiceLocator
{
private static IContainer container;
public static IContainer Container
{
get
{
if (container == null)
{
container = new Container();
}
return container;
}
}
}
Register everything as normal in your composition root using the ServiceLocator class. Then to use:
public class MyClass
{
public void DoSomething()
{
var blah = ServiceLocator.Container.Resolve<IBlah>();
}
}

How can I use windsor to give me an instance of an object that isn't registered?

So I have windsor set up and all of my services registered. I have a class that requires these services in the ctor, but this class isn't registered with windsor as it does not have an interface and I don't want to give it one for the sake of dependency resolution. What I'm really interested in, is having windsor resolve and inject my registered dependencies and hand me back an initialized class -- basically a factory.
The problem that I'm running into is that windsor throws because the dependent class has not been registered:
void Main()
{
var container = new WindsorContainer();
container.Register(Component
.For<ITestInterface>()
.ImplementedBy<TestImpl>()
.LifestyleTransient());
var c = container.Resolve<TestClass>(); // throws because TestClass isn't registered
c.Run();
}
public class TestClass
{
private ITestInterface _d;
public TestClass(ITestInterface d)
{
_d = d;
}
public void Run()
{
_d.Do();
}
}
public interface ITestInterface
{
void Do();
}
public class TestImpl : ITestInterface
{
public void Do()
{
Console.WriteLine("done");
}
}
What I don't want to end up doing, is something like this:
var dependency1 = container.Resolve<ITestInterface>();
var c = new TestClass(dependency1);
c.Run();
Because now we're in service locator territory. But more importantly, classes that have several dependencies...well that could get tedious.
How can I get windsor to have the desired factory effect? Or is this even possible with Windsor? I recall this being possble with Ninject.
So the popular response seems to be "Just register the component" which I really don't like at all because for such a simple use case, I could end up with a config class with hundreds of unnecessary registrations. That's kind of silly. So in the meanwhile, until I discover some built in functionality for this, I've create a cheesy extension that should land me somewhere in the middle. This extension simply takes the type, registers it for you and then tries to resolve it. That way, it's leveraging Windsor's own ctor resolution logic:
public static class WindsorExtentions
{
public static T Construct<T>(this IWindsorContainer container)
where T : class
{
if (!container.Kernel.HasComponent(typeof(T)))
container.Register(Component.For<T>());
var instance = container.Resolve<T>();
return instance;
}
}
What I would really like to do is register it, resolve it, then unregister it, but it appears that the RemoveComponent method has been removed in 3.0. This should be fine in the meanwhile. It obviously isn't all-inclusive with use cases, but when you have loads of proxy classes that have several required dependencies to be injected, I think this helps.
Usage:
var myClassWithDependencies = myContainer.Construct<MyClassWithDependencies>();
public class MyClassWithDependencies
{
public MyClassWithDependencies(
IFacebookClient facebookClient,
IGooglePlusClient googlePlusClient,
ITwitterClient twitterClient,
ISalesforceClient salesforceClient,
IReportRepository reportRepo,
IUserRepository userRepo)
{
}
}

Simple Injector - inject container property

I want to inject Container property via SimpleInjector. I didn't find any functionality of SimpleInjector for that.
Then I wanted to register self container to itself, but Container has no interface.
I want this functionality because I don't to transfer Container object via constructor - because why if I can use auto inject of register objects.
My usage idea:
var container = new Container();
container.Options.AutowirePropertiesWithAttribute<InjectableProperty>();
container.Register<ISomething, Something>(Lifestyle.Singleton);
ISomething:
public interface ISomething
{
void SomeMethod();
}
Something class:
public class Something : ISomething
{
public void SomeMethod()
{
var environment = _container.GetInstance<IEnvironment>();
environment.DoSomething();
}
[InjectableProperty] // - maybe it is not possible (I don't know it)
Container Container {get;set;}
}
Do you have any idea to achieve that?
Thank you very much.
Prevent having your application code depend upon the container. The only place in your application that should know about the existence of your DI library is the Composition Root (the place where you register all your dependencies).
Instead of letting each class call back into the container (which is called the Service Locator anti-pattern), prefer using Dependency Injection. With Dependency Injection you inject dependencies instead of asking for them.
So you can rewrite your class to the following:
public class Something : ISomething
{
private readonly IEnvironment environment;
public Something (IEnvironment environment)
{
this.environment = environment;
}
public void SomeMethod()
{
this.environment.DoSomething();
}
}
Also, prevent doing any logic in your constructors besides storing the incoming dependencies. This allows you to compose object graphs with confidence.
In some cases however, it can still be useful to inject the Container into another class. For instance when creating a factory class that is located inside the Composition Root. In that case you can still use constructor injection, like this:
// Defined in an application layer
public interface IMyFactory
{
IMyService CreateService();
}
// Defined inside the Composition Root
public class MyFactory : IMyFactory
{
private readonly Container container;
public MyFactory(Containter container)
{
this.container = container;
}
public IMyService CreateService(ServiceType type)
{
return type == ServiceType.A
? this.container.GetInstance<MyServiceA>()
: this.container.GetInstance<MyServiceB>();
}
}
If Simple Injector detects a Container constructor argument, it will inject itself into the constructor automatically.

looking for various way of implemention Dependency injection using unity

i am new in Dependency injection. i just got familiar how to implement dependency injection with Interface injection but we know that Dependency injection can be implemented with three way or may be more and those are :-
Interface injection: The service provides an interface which consumers must implement. The interface exposes specific behaviors at run time.
Setter injection: The dependent object exposes a “setter” method to inject the dependency.
Constructor injection: Dependencies are injected through the class constructor
so i am looking for few sample code which can help me to understand how to implement Dependency injection using either Setter injection or Constructor injection using unity. any help with small small code for different way of implementing dependency injection will be appreciated.
i know only Interface injection using unity. here is my code which works fine using Interface injection with unity.
public interface ILogger
{
void Write(string message);
}
We have define three classes as follows.
public class FileLogger : ILogger
{
public void Write(string message)
{
//Do somthing
}
}
public class SQLLogger : ILogger
{
public void Write(string message)
{
//Do somthing
}
}
public class WindowsEventLogger : ILogger
{
public void Write(string message)
{
//Do somthing
}
}
Need to register and map these classes with interface in configuration file (i.e. app.config).
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias type="UnityTest.ILogger, UnityTest" alias="ILogger" />
<namespace name="UnityTest"/>
<container>
<register mapTo="UnityTest.FileLogger, UnityTest" name="MyFileLogger" type="ILogger"/>
<register mapTo="UnityTest.SQLLogger, UnityTest" name="MySQLLogger" type="ILogger"/>
<register mapTo="UnityTest.WindowsEventLogger, UnityTest" name="MyWindowsEventLogger" type="ILogger"/>
</container>
</unity>
Note: name attribute is important in register tag.
Finally we have to use this map into our code. So, we have to know that for which one is preferable for specific country.
A dictionary object can be use to keep this mapping as follows.
IDictionary<string, string> loggers = new Dictionary<string, string>();
loggers.Add("USA", "MyFileLogger");
loggers.Add("GBR", "MySQLLogger");
loggers.Add("IN", "MyWindowsEventLogger");
You can populate it from database, xml or another source, and now it's time to call the Write method.
IUnityContainer container = new UnityContainer();
container.LoadConfiguration();
ILogger logger = container.Resolve<ILogger>(loggers[objUser.countryCode]);
logger.Write("Hello World");
New question
I found a sample code for construction injection with unity but still one thing is not clear. Here is the code.
public class CustomerService
{
public CustomerService(LoggingService myServiceInstance)
{
// work with the dependent instance
myServiceInstance.WriteToLog("SomeValue");
}
}
IUnityContainer uContainer = new UnityContainer();
CustomerService myInstance = uContainer.Resolve<CustomerService>();
When we write uContainer.Resolve<CustomerService>(); then we are not sending any instance of LoggingService class then how we can create instance of CustomerService class because it's constructor require instance of LoggingService.
This area is not clear. Please explain to me how it works.
Another question is [Dependency] attribute: what it does, and when a method needs to be decorated with the [Dependency] attribute.
With your code as a base.
if you have some class that depends on ILogger, and you have a default registration for ILogger (a registration without name)
IUnityContainer container = new UnityContainer();
//fixed
//by default RegisterType will create new instance of the type every time
//the container resolves the dependancy
container.RegisterType<ILogger,SomeLoggerImplementation>();
container.RegisterType<Foo>();
container.RegisterType<Bar>();
//will create a new instance of SomeLoggerImplementation using a default ctor, pass it to the constructor of Foo and return the instance of Foo
//if SomeLoggerImplementation has some other dependancies they can be registered in the container too!
var foo = container.Resolve<Foo>();
//will create a new instance of SomeLoggerImplementation using a default ctor, create a new instance of Bar,
//Set the value of the Property Logger (but not the Logger2), and return the instance of Bar
var bar = container.Resolve<Bar>();
//Constructor injection
public class Foo
{
private ILogger _logger;
public Foo(ILogger logger)
{
//if Foo is resolved from the container , the value for the logger parameter will be provided from the container
_logger = logger;
}
}
//property injection
public class Bar
{
//If Bar is resolvced from the container the value for the Logger property will also be provided from the container
[Dependency]
public ILogger Logger { get; set; }
//this will not be injected
public ILogger Logger2 { get; set; }
public Bar()
{
}
}
First register the classes to be solved to unity (in this case register Test class to unity). When you try to resolve an instance of Test class using unity, it will resolve ILogger too. You may refer to injection attributes from msdn
setter injection;
public class Test : ITest
{
[Dependency("MyFileLogger")]
public ILogger Logger
{
get { return iLogger; }
set { iLogger = value; }
}
}
constructor injection;
public class Test : ITest
{
public Test([Dependency("MyFileLogger")] ILogger logger)
{
//// you will have an instance of MyFileLogger
}
}
For the second part of your question, since LoggingService is also registered to unity, when CustomerService is tried to be resolved, it will use constructor injection to resolve the LoggingService parameter. In other words, when container tries to resolve CustomerService; it understands that LoggingService is needed to resolve it. Then it first resolves LoggingService parameter and then tries to resolve CustomerService.

With Unity how do I inject a named dependency into a constructor?

I have the IRespository registered twice (with names) in the following code:
// Setup the Client Repository
IOC.Container.RegisterType<ClientEntities>(new InjectionConstructor());
IOC.Container.RegisterType<IRepository, GenericRepository>
("Client", new InjectionConstructor(typeof(ClientEntities)));
// Setup the Customer Repository
IOC.Container.RegisterType<CustomerEntities>(new InjectionConstructor());
IOC.Container.RegisterType<IRepository, GenericRepository>
("Customer", new InjectionConstructor(typeof(CustomerEntities)));
IOC.Container.RegisterType<IClientModel, ClientModel>();
IOC.Container.RegisterType<ICustomerModel, CustomerModel>();
But then when I want to resolve this (to use the IRepository) I have to do a manual resolve like this:
public ClientModel(IUnityContainer container)
{
this.dataAccess = container.Resolve<IRepository>(Client);
.....
}
What I would like to do is to have it resolved in the constructor (just like IUnityContainer). I need some way to say which named type to resolve to.
Something like this: (NOTE: Not real code)
public ClientModel([NamedDependancy("Client")] IRepository dataAccess)
{
this.dataAccess = dataAccess;
.....
}
Is there a way to make my fake code work?
You can configure dependencies with or without names in the API, attributes, or via the config file. You didn't mention XML above, so I'll assume you're using the API.
To tell the container to resolve a named dependency, you'll need to use an InjectionParameter object. For your ClientModel example, do this:
container.RegisterType<IClientModel, ClientModel>(
new InjectionConstructor( // Explicitly specify a constructor
new ResolvedParameter<IRepository>("Client") // Resolve parameter of type IRepository using name "Client"
)
);
This tells the container "When resolving ClientModel, call the constructor that takes a single IRepository parameter. When resolving that parameter, resolve with the name 'Client' in addition to the type."
If you wanted to use attributes, your example almost works, you just need to change the attribute name:
public ClientModel([Dependency("Client")] IRepository dataAccess)
{
this.dataAccess = dataAccess;
.....
}
This is a very late response but the question still shows up in Google.
So anyways, 5 years later...
I have a pretty simple approach. Usually when you need to use "named dependency" it's because you're trying to implement some kind of strategy pattern. In that case, I simply create a level of indirection between Unity and the rest of my code called the StrategyResolver to not be directly depending on Unity.
public class StrategyResolver : IStrategyResolver
{
private IUnityContainer container;
public StrategyResolver(IUnityContainer unityContainer)
{
this.container = unityContainer;
}
public T Resolve<T>(string namedStrategy)
{
return this.container.Resolve<T>(namedStrategy);
}
}
Usage:
public class SomeClass: ISomeInterface
{
private IStrategyResolver strategyResolver;
public SomeClass(IStrategyResolver stratResolver)
{
this.strategyResolver = stratResolver;
}
public void Process(SomeDto dto)
{
IActionHandler actionHanlder = this.strategyResolver.Resolve<IActionHandler>(dto.SomeProperty);
actionHanlder.Handle(dto);
}
}
Registration:
container.RegisterType<IActionHandler, ActionOne>("One");
container.RegisterType<IActionHandler, ActionTwo>("Two");
container.RegisterType<IStrategyResolver, StrategyResolver>();
container.RegisterType<ISomeInterface, SomeClass>();
Now, the nice thing about this is that I will never have to touch the StrategyResolver ever again when adding new strategies in the future.
It's very simple. Very clean and I kept the dependency on Unity to a strict minimum. The only time I would have touch the StrategyResolver is if I decide to change container technology which is very unlikely to happen.
Hope this helps!
Edit: I don't really like the accepted answer because when you use the Dependency attribute in your service's constructor you actually have a hard dependency on Unity. The Dependency attribute is part of the Unity library. At that point you might as well pass an IUnityContainer dependency everywhere.
I prefer having my service classes depend on objects that I completely own instead of having a hard dependency on an external library all over the place. Also using Dependency attribute makes the constructors signatures less clean and simple.
Furthermore, this technique allows to resolve named dependencies at runtime without having to hardcode the named dependencies in the constructor, in the application configuration file or use InjectionParameter which are all methods that require to know what named dependency to use at design time.
Edit (2016-09-19):
For those that might wonder, the container will know to pass itself when you are requesting IUnityContainer as dependency, as shown in the StrategyResolver constructor signature.
Edit (2018-10-20):
Here's another way, simply using a factory:
public class SomeStrategyFactory : ISomeStrategyFactory
{
private IStrategy _stratA;
private IStrategy _stratB;
public SomeFactory(IStrategyA stratA, IStrategyB stratB)
{
_stratA = stratA;
_stratB = stratB;
}
public IStrategy GetStrategy(string namedStrategy){
if (namedStrategy == "A") return _stratA;
if (namedStrategy == "B") return _stratB;
}
}
public interface IStrategy {
void Execute();
}
public interface IStrategyA : IStrategy {}
public interface IStrategyB : IStrategy {}
public class StrategyA : IStrategyA {
public void Execute(){}
}
public class StrategyB : IStrategyB {
public void Execute() {}
}
Usage:
public class SomeClass : ISomeClass
{
public SomeClass(ISomeStrategyFactory strategyFactory){
IStrategy strat = strategyFactory.GetStrategy("HelloStrategy");
strat.Execute();
}
}
Registration:
container.RegisterType<ISomeStrategyFactory, SomeStrategyFactory>();
container.RegisterType<IStrategyA, StrategyA>();
container.RegisterType<IStrategyB, StrategyB>();
container.RegisterType<ISomeClass, SomeClass>();
This 2nd suggestion is the same thing but using the factory design pattern.
Hope this helps!
You should be able to use ParameterOverrides
var repository = IOC.Container.Resolve<IRepository>("Client");
var clientModel = IOC.Container.Resolve<ClientModel>(new ParameterOverrides<ClientModel> { {"dataAccess", repository } } );
edit:
I'm not sure why you're passing around the UnityContainer - personally, we inject our dependencies into the constructor themselves (which is "normal" from what I've seen). But regardless, you can specify a name in your RegisterType and Resolve methods.
IOC.Container.RegisterType<IRepository, GenericRepository>("Client");
IOC.Container.Resolve<IRepository>("Client");
and it will give you the type you registered for that name.
Don't do this - just create a class ClientRepository : GenericRepository { } and utilise the Type system.

Categories

Resources