Batch registration in Unity?

Jan 22, 2013 at 9:44 PM
Edited Jan 22, 2013 at 9:50 PM

In Ninject, you can define an implementaion of NinjectModule, then pass an instance of it to container's constructor.

 

class Module1 : NinjectModule
{
    public void Load() { Bind<IMyType>().To<MyType>(); }
}

class Module2 : NinjectModule
{
    public void Load() { ... }
}

class Program
{
    public static void Main()
    {
        IKernel kernel = new StandardKernel(new Module1(), new Module2(), ...);
        ...
    }
}

 

Is there any same functionality in Unity 2.x?

Jan 23, 2013 at 1:33 AM

No, but the container has itself as a registration against IUnityContainer.  If you Resolve a type and take a dependency on IUnityContainer you will be able to add registrations to the supplied instance.  

If registering in the constructor doesn't feel right, then you can annotate a method ( lets call it "Load" ) with [Dependency] and Unity will call the method post construction and you can register from that method.

 

You could either resolve the concretes directly, or Register the "loader" modules and use ResolveAll.

 

If you're only using the Load method in the Module, then I would consider creating an generic extension method for IUnityContainer.

Jan 23, 2013 at 8:49 AM

If you derive a class from UnityContainerExtension you can perform registration tasks inside the extension's Initialize() method.

var container = new UnityContainer();
container.AddNewExtension<Module1>();

public class Module1 : UnityContainerExtension
{
  protected override void Initialize()
  {
    this.Container.RegisterType<IMyType, MyType>();
  }
}

Jan 23, 2013 at 12:41 PM

Thank you, that's exactly what I was searching for!