Unity Dependency Injection has given us lot of flexibility in terms of customizations and suits to our requirement. There has been good reference and api for Unity MVC , Web API and WCF service. Here is the good free online e-book to start from scratch. It covers everything from DI, AOP, exception handling, caching and customization.
http://blogs.msdn.com/b/agile/archive/2013/08/20/new-guide-dependency-injection-with-unity.aspx
If you looking for creating instance with Unity DI for any class this is what we must do.
Injection constructor
Injection Methods
Few things to keep in mind.
1. We register interface/Class for object reference.
2. We set resolver for each class object
3. We get the resolver.
Option 1
public class MyObject
{
public MyObject(SomeClassA objA, SomeClassB objB)
{
...
}
[InjectionConstructor]
public MyObject(DependentClassA depA, DependentClassB depB)
{
...
}
}
IUnityContainer uContainer = new UnityContainer();
MyObject myInstance = uContainer.Resolve();
Option 2
IUnityContainer container= new UnityContainer();
http://blogs.msdn.com/b/agile/archive/2013/08/20/new-guide-dependency-injection-with-unity.aspx
If you looking for creating instance with Unity DI for any class this is what we must do.
Injection constructor
Injection Methods
Few things to keep in mind.
1. We register interface/Class for object reference.
2. We set resolver for each class object
3. We get the resolver.
Option 1
public class MyObject
{
public MyObject(SomeClassA objA, SomeClassB objB)
{
...
}
[InjectionConstructor]
public MyObject(DependentClassA depA, DependentClassB depB)
{
...
}
}
IUnityContainer uContainer = new UnityContainer();
MyObject myInstance = uContainer.Resolve
Option 2
IUnityContainer container= new UnityContainer();
container.RegisterType<MyObject>(
new InjectionConstructor(
new ResolvedParameter<DependentClassA>(), new ResolvedParameter<DependentClassB>()));
var instance= container.Resolve<MyObject>();
We can even have global configuration to resolve all our object instance for any class library.
No comments :
Post a Comment