Create modules using Unity (Ioc)

Asked

Viewed 398 times

3

In an application using a multi-tier (n-layer) architecture, we have the infrastructure layer where we use an Ioc container to record 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 can grow, I would like to be able to separate dependencies by modules. I know that in Ninject it is possible to create these modules by creating a class inheriting from Ninjectmodule and overwriting the Load method. After the creation of these modules it is possible to load them when necessary (one or more modules)

Could anyone tell me if there is something similar in Unity? If there is, could they indicate some example or model?

2 answers

2

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

I have a DDD project on Github - already quite dated, by the way, but still valid for your question - where I have the injector isolated and modularized. However I am using Simpleinjector.

I recommend you even study a substitution, since Simpleinjector is one of the fastest injectors on the market, and also very well recommended. I also strongly recommend that you avoid Ninject, since it is one of the - if not the - slowest in 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>)}
        };
    }
}

1

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.