简体   繁体   中英

Remove Dependency on IoC Container

After reading more and more about IoC containers, I read this post about not having IoC.Resolve() etc in your code.

I'm really curious to know then, how can I remove the dependency on the container?

I'll want to write code like the following:

public void Action()
{
    using(IDataContext dc = IoC.Resolve<IDataContext>())
    {
        IUserRepository repo = IoC.Resolve<IUserRepository>();
        // Do stuff with repo...
    }
}

But how can I get rid of the IoC.Resolve calls? Maybe I need a better understanding of DI...

Thanks in advance.

Generally speaking, most dependencies can be injected into your class at the time it is created. However, in this particular case, you need a component that must be created on demand at the time of use. In such cases, it is very difficult to completely remove dependency on an IoC container. My approach has always been to create a factory that is injected into the class at creation time, which in turn encapsulates all direct IoC usage. This allows your factories to be mocked for testing, rather than the IoC container itself...which tends to be a lot easier:

// In Presentation.csproj
class PresentationController
{
    public PresentationController(IDataContextFactory dataContextFactory, IRepositoryFactory repositoryFactory)
    {
        #region .NET 4 Contract
        Contract.Requires(dataContextFactory != null);
        Contract.Requires(repositoryFactory != null);
        #endregion

        _dataContextFactory = dataContextFactory;
        _repositoryFactory = repositoryFactory;
    }

    private readonly IDataContextFactory _dataContextFactory;
    private readonly IRepositoryFactory _repositoryFactory;

    public void Action()
    {
        using (IDataContext dc = _dataContextFactory.CreateInstance())
        {
            var repo = _repositoryFactory.CreateUserRepository();
            // do stuff with repo...
        }
    }
}

// In Factories.API.csproj
interface IDataContextFactory
{
    IDataContext CreateInstance();
}

interface IRepositoryFactory
{
    IUserRepository CreateUserRepository();
    IAddressRepository CreateAddressRepository();
    // etc.
}

// In Factories.Impl.csproj
class DataContextFactory: IDataContextFactory
{
    public IDataContext CreateInstance()
    {
        var context = IoC.Resolve<IDataContext>();
        // Do any common setup or initialization that may be required on 'context'
        return context;
    }
}

class RepositoryFactory: IRepositoryFactory
{
    public IUserRepository CreateUserRepository()
    {
        var repo = IoC.Resolve<IUserRepository>();
        // Do any common setup or initialization that may be required on 'repo'
        return repo;
    }

    public IAddressRepository CreateAddressRepository()
    {
        var repo = IoC.Resolve<IAddressRepository>();
        // Do any common setup or initialization that may be required on 'repo'
        return repo;
    }

    // etc.
}

The benefit of this approach is, while you can not completely eliminate the IoC dependency itself, you can encapsulate it in a single kind of object (a factory), decoupling the bulk of your code from the IoC container. This improves your codes agility in light of, say, switching from one IoC container to another (ie Windsor to Ninject).

It should be noted, an interesting consequence of this, is that your factories are usually injected into their dependents by the same IoC framework they use. If you are using Castle Windsor, for example, you would create configuration that tells the IoC container to inject the two factories into your business component when it is created. The business component itself may also have a factory...or, it may simply be injected by the same IoC framework into a higher-level component, etc. etc., ad inf.

I was on a project a while ago that hadn't settled on an IoC container. They managed the uncertainty by disallowing non-IoC specific features of their container and also by wrapping Resolve with their own class. This is also something I've seen advocated a few times in blog posts... remove the last dependency, the dependency on the dependency injection container.

This is a workable technique, but at some point you have to choose the tools you use and be willing to accept that you'll pay costs to switch to alternative tools. For me, IoC containers fall into the category of things you probably ought to embrace wholeheartedly, so I question this level of factoring. If you want to look into this further, I suggest the following link:

http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion

One alternative is to re-write the method to accept Func<T> delegates. This removes the dependency from the method and allows you to unit test it with a mock:

public void Action(Func<IDataContext> getDataContext, Func<IUserRepository> getUserRepository)
{
    using(IDataContext dc = getDataContext())
    {
        IUserRepository repo = getUserRepository();
        // Do stuff with repo...
    }
}

I blogged about this very issue recently:

有第二个依赖注入器注入第一个,第一个注入第二个。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM