Multiple-Constructor Injection using Unity IOC

Unity, and the dependency injection design pattern itself, really becomes useful is when the container generates instances of objects that have dependencies. It can automatically resolve the dependent object types required by the objects it creates, generate the appropriate concrete types, and then inject these concrete instances into the object it is creating.

The following shows a schematic view of the dependency injection process that Unity can accomplish.

Cc816062.9444d795-6e6e-4d23-ab27-77467e20123a(en-us,MSDN.10).png

The following are the types of injection together with descriptions of how they are applied using Unity:

  • Constructor injection. This type of injection occurs automatically. When you create an instance of an object using the Unity container, it will automatically detect the constructor with the largest number of parameters and execute this, generating instances of each object defined in the constructor parameters. It resolves each parameter type through the container, applying any registrations or mappings for that type. If you want to specify a particular constructor for Unity to use, you can add the InjectionConstructor attribute to that constructor in the target class.
  • Property (setter) injection. This type of injection is optional. You can add the Dependency attribute to any property declarations that you want Unity to resolve through the container. Unity will resolve that property type and set the value of the property to an instance of the resolved type.
  • Method call injection. This type of injection is also optional. You can add the InjectionMethod attribute to any method declarations where you want Unity to resolve the method parameters through the container. Unity will resolve each parameter type and set the value of that parameter to an instance of the resolved type, and then it will execute the method. Method call injection is useful if you need to execute some type of initialization method within the target object.

Via http://msdn.microsoft.com/en-us/library/cc816062.aspx

Multiple-Constructor Injection Using an Attribute

When a target class contains more than one constructor with the same number of parameters, you must apply the InjectionConstructor attribute to the constructor that the Unity container will use to indicate which constructor the container should use. As with automatic constructor injection, you can specify the constructor parameters as a concrete type, or you can specify an interface or base class for which the Unity container contains a registered mapping.

e.g.

public class MyObject {

public MyObject(SomeOtherClass myObjA)   { …  }

[InjectionConstructor]
public MyObject(MyDependentClass myObjB)  {  … }
}

In your run-time code, use the Resolve method of the container to create an instance of the target class. The Unity container will instantiate the dependent concrete class defined in the attributed constructor and inject it into the target class. For example, the following code shows how you can instantiate the example target class named MyObject containing an attributed constructor that has a dependency on a class named MyDependentClass.

e.g.

IUnityContainer uContainer = new UnityContainer();
MyObject myInstance = uContainer.Resolve<MyObject>();

How Unity Resolves Target Constructors and Parameters

When a target class contains more than one constructor, Unity will use the one that has the InjectionConstructor attribute applied. If there is more than one constructor, and none carries the InjectionConstructor attribute, Unity will use the constructor with the most parameters. If there is more than one such constructor (more than one of the “longest” with the same number of parameters), Unity will raise an exception.

Constructor Injection with Existing Objects

If you use the RegisterInstance method to register an existing object, constructor injection does not take place on that object because it has already been created outside of the influence of the Unity container. Even if you call the BuildUp method of the container and pass it the existing object, constructor injection will never take place because the constructor will not execute. Instead, mark the constructor parameter containing the object you want to inject with the Dependency attribute to force property injection to take place on that object, and then call the BuildUp method. This is a similar process to property (setter) injection. It ensures that the dependent object can generate any dependent objects it requires. For more details, see Annotating Objects for Property (Setter) Injection.

Via http://msdn.microsoft.com/en-us/library/cc440940.aspx

What Is The Difference Between an IoC Container and MEF?

 

What Is The Difference Between an IoC Container and MEF?

MEF allows you to write your application as a series of much simpler mini applications, and have those brought together to create a much great whole

IoC container = service level components, MEF = Autonomous Components. A MEF "part" will probably use an IoC container

I recommend reading them highly, they will do a much better job than I could at explaining the detail of the decision points, Should I use MEF for my general IoC needs? and Should I use MEF with an IoC container?

Via What Is The Difference Between an IoC Container and MEF? – Jak Charlton – Insane World – Devlicio.us – Just the Tasty Bits

Unity IoC in 30 seconds

Object Factory

Container-Configured Registration of Types

As an example of using the overloads of the RegisterType and Resolve methods, the following code registers a mapping for an interface named IMyService, and specifies that the container should return an instance of the CustomerService class (which implements the IMyService interface).

IUnityContainer myContainer = new UnityContainer();
myContainer.RegisterType<ILoggingService, LoggingService>();
ILoggingService myServiceInstance = myContainer.Resolve<ILoggingService>();

Container-Configured Registration of Existing Object Instances

As an example of using the overloads of the RegisterInstance and Resolve methods, the following code registers an existing instance of a class named LoggingService that implements the interface IMyService and then retrieves that instance.

IUnityContainer myContainer = new UnityContainer();
LoggingService myExistingObject = new LoggingService();
myContainer.RegisterInstance<ILoggingService>(myExistingObject);
ILoggingService myServiceInstance = myContainer.Resolve<ILoggingService>();

Constructor Injection

As an example of constructor injection, if a class that developers instantiate using the Resolve method of the Unity container has a constructor that defines one or more dependencies on other classes, the Unity container will automatically create the dependent object instance specified in parameters of the constructor. For example, the following code shows a class named CustomerService that has a dependency on a class named ILoggingService.

public class CustomerService
{
  public CustomerService(ILoggingService myServiceInstance)
  {
    // work with the dependent instance
    myServiceInstance.WriteToLog("SomeValue");
  }
}

Property (Setter) Injection

In addition to constructor injection, described earlier, the Unity Application Block supports property and method call injection. The following code demonstrates property injection. A class named ProductService exposes as a property a reference to an instance of another class named SupplierData (not defined in the following code). To force dependency injection of the dependent object, developers must apply the Dependency attribute to the property declaration, as shown in the following code.

public class ProductService
{
  private ISupplierData supplier;

  [Dependency]
  public ISupplierData SupplierDetails
  {
    get { return supplier; }
    set { supplier = value; }
  }
}

Highlights of the Unity Application Block


The Unity Application Block includes the following features:

  • It provides a mechanism for building (or assembling) instances of objects, which may contain other dependent object instances.
  • It exposes RegisterType methods that support configuring the container with type mappings and objects (including singleton instances) and Resolve methods that return instances of built objects that can contain any dependent objects.
  • It provides inversion of control (IoC) functionality by allowing injection of preconfigured objects into classes built by the application block. Developers can specify an interface or class type in the constructor (constructor injection), or apply attributes to properties and methods to initiate property injection and method call injection.
  • It supports a hierarchy for containers. A container may have child container(s), allowing object location queries to pass from the child out through the parent container(s).
  • It can read configuration information from standard configuration systems, such as XML files, and use it to configure the container.
  • It makes no demands on the object class definition. There is no requirement to apply attributes to classes (except when using property or method call injection), and there are no limitations on the class declaration.
  • It supports custom container extensions that developers can implement; for example, methods to allow additional object construction and container features such as caching.

Via Introduction to Unity

Upgrading the default ASP.NET MVC project with IoC and the Unity Controller Factory

 

The first part is easy, just grab the Unity DLLs and reference them in your MVC project. At this point, you’re now free to use Unity to inject whatever you feel like. Rigging up the controller factory so that it will use Unity to resolve controllers is equally easy because the mvc contrib codeplex site has already created a class called UnityControllerFactory that does just this. Once you’ve added references to Unity and Mvc.Contrib.Unity from your MVC project, you can change your global.asax.cs file to look something like this:

if (_container == null)
            {
                _container = new UnityContainer();             
                ControllerBuilder.Current.SetControllerFactory(typeof(UnityControllerFactory));                               
               
                _container.RegisterType(typeof(HomeController), typeof(HomeController));
                _container.RegisterInstance(typeof(AccountController), new AccountController());               
            }

 

Via Upgrading the default ASP.NET MVC project with IoC and the Unity Controller Factory [The .NET Addict’s Blog]

Ninject Cheat Sheet

image

Constructor Injection

class Samurai {
  private readonly IWeapon _weapon;

[Inject] // limit to 1 constructor ONLY, use Property Injection if you need more than 1 however the order is non-deterministic. public Samurai(IWeapon weapon) { _weapon = weapon; }

public void Attack(string target) { _weapon.Hit(target); } }

 

Activation Process

For instance,

//note: type bindings are collected into groups called modules.
//You can create as many modules as you'd like, and pass them all to the kernel's constructor. 
//e.g. IKernel kernel = new StandardKernel(new Module1(), new Module2(), ...);
class WarriorModule : StandardModule {
  public override Load() {
       //note: Module isn’t limited to a boring, static collection of bindings. You can always do more creative things like conditional bindings & contextual bindings.
    Bind<IWeapon>().To<Sword>(); // type binding
    Bind<Samurai>().ToSelf(); // self-bound, only allow in concrete type. 
  }
}
class Program {
  public static void Main() {
    IKernel kernel = new StandardKernel(new WarriorModule());
    Samurai warrior = kernel.Get<Samurai>();
    warrior.Attack("the evildoers");
  }
}

 

The activation process for the Samurai type is as follows. The number to the left indicates the depth at which the activation is occurring, and some steps have been left out for clarity:

  • (1) The kernel resolves the self-binding for the Samurai type that was defined in the WarriorModule.
  • (1) The kernel asks the Samurai‘s TransientBehavior to resolve an instance.
  • (1) The Samurai’s TransientBehavior asks the binding’s provider to create a new instance.
  • (2) The Samurai’s StandardProvider asks the kernel to resolve an instance of IWeapon.
  • (2) The kernel resolves the binding from IWeapon to Sword that was defined in the WarriorModule.
  • (2) The kernel asks the Sword‘s TransientBehavior to resolve an instance.
  • (2) The Sword‘s TransientBehavior asks the binding’s provider to create a new instance.
  • (2) The Sword‘s StandardProvider calls the Sword‘s parameterless constructor.
  • (2) The kernel returns the newly-created instance of Sword.
  • (1) The Samurai‘s StandardProvider calls the Samurai‘s injection constructor, passing it the instance of Sword as an argument.
  • (1) The kernel returns the newly-created instance of Samurai to the site of the method call in Main().

 

Activation Behavior

There are four built-in behaviors available in Ninject. Attribute is class level:

TransientBehavior [Transient]

A new instance of the type will be created each time one is requested.

SingletonBehavior [Singleton]

Only a single instance of the type will be created, and the same instance will be returned for each subsequent request.

OnePerThreadBehavior [OnePerThread]

One instance of the type will be created per thread.

OnePerRequestBehavior [OnePerRequest]

One instance of the type will be created per web request, and will be destroyed when the request ends.

Instead of relying on attributes, you can also define the behavior when you declare the binding:

Bind<Shogun>().ToSelf().Using<SingletonBehavior>();

Contextual Binding

For instance,
Bind<IWeapon>().To<Sword>();
Bind<IWeapon>().To<Shuriken>().Only(When.Context.Target.HasAttribute<RangeAttribute>()); // using attrib
Bind<IWeapon>().To<Shuriken>().Only(When.Context.Tag == "range"); // using attrib: [Inject, Tag("range")]
Bind<IWeapon>().To<Shuriken>().Only(When.Context.Service.Name.StartsWith(“Foo”); // using convention
Bind<IWeapon>().To<Shuriken>().Only(When.Context.Target.Name.BeginsWith(“Remote”); // using convention
// note: IWeapon is the “Service Type”(generally an interface of abstract type) 
// while Sword/Shuriken are “Impl/Target Type”

 

For a complete tutorial visit http://dojo.ninject.org/