Create modules using Unity (IoC)

3

In an application using a multilayer (n-layer) architecture, we have the infrastructure layer where we use an IoC container to register the required dependencies. In a prototype I'm working on, I'm using the Unity Application Block Unity as a container. As it will be a project that could grow, I would like to be able to separate dependencies by modules. I know that in Ninject you can create these modules by creating a class inheriting from NinjectModule and overriding the Load method. After creating these modules you can load them as needed (one or more modules)

Can anyone tell me if there is something similar in Unity? If it exists, could you indicate any example or template?

    
asked by anonymous 13.01.2015 / 11:55

2 answers

2

I know the question is about Unity, but I hope to help anyway.

I have a DDD project in GitHub - already quite dated, incidentally, but still valid for your question - where I have the injector isolated and modularized. But I'm using SimpleInjector .

I recommend, even if you study a replacement, since SimpleInjector is a of the fastest injectors on the market , and also very well recommended. I also strongly recommend that you avoid Ninject, as it is one of the - if not the - slowest on the market.

IoC:

public class IoC
{
    private Container _container;
    public Container Container
    {
        get
        {
            if (_container != null) return _container;

            _container = new Container();

            Register(_container, InfrastructureInjectors.GetInjectors());
            Register(_container, RepositoryInjectors.GetInjectors());
            Register(_container, ApplicationInjectors.GetInjectors());
            Register(_container, ServiceInjectors.GetInjectors());

            return _container;
        }
    }
} 

Module:

public class InfrastructureInjectors
{
    public static Dictionary<Type, Type> GetInjectors()
    {
        return new Dictionary<Type, Type>
        {
            {typeof (IContextManager<MainContext>), typeof (ContextManager<MainContext>)},
            {typeof (IUnitOfWork<MainContext>), typeof (UnitOfWork<MainContext>)}
        };
    }
}
    
29.07.2016 / 11:12
1

As far as I know, it does not exist. It is however possible to register modules dynamically, and a solution to this problem could be to use something like MEF (Managed Extensibility Framework), included in .NET 3.5 and above, to find classes in DLLs in any folder or subfolder that implements a given contract (interface or abstract base class).

    
13.01.2015 / 13:39