17

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.

Community
  • 1
  • 1
TheCloudlessSky
  • 18,608
  • 15
  • 75
  • 116

5 Answers5

17

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 (i.e. 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.

jrista
  • 32,447
  • 15
  • 90
  • 130
  • Thanks for the answer. The only problem is that the IoC that I'm using should have a scope, relative to a `using` statement. Then if I Resolve say `IDataContext` it will resolve the *single instance* for that particular scope. I don't want my controllers etc to be aware of an IoC container, but is there really any way around this? – TheCloudlessSky Jul 01 '10 at 10:54
  • What I'm wondering is if a Controller should be able to call IoC.Resolve? If not, who should be making this call? – TheCloudlessSky Jul 01 '10 at 12:01
  • Could you explain a little more about this scope? What IoC container are you using? Generally speaking, coupling any of your code to the container framework in any way is a negative kind of coupling...you should avoid that at all costs. In my experience, a scope (or context) is rarely, if ever, required for an IoC container to work. If it does work that way, I would find an alternative container, or find a way to supply that context to the factories that resolve your objects and keep your IoC framework decoupled as much as possible. – jrista Jul 01 '10 at 16:24
  • Well actually I'm trying to write my own *very simple* IoC container. I'm doing it mostly for my own learning. I'm using ASP.NET MVC and so regardless of what IoC container, who makes the call to Resolve. I understand about using the Factory, but where does the Factory lie? Should it be the only thing in the application that has a reference to the container? – TheCloudlessSky Jul 01 '10 at 16:56
  • Yes, the factories should be the only things that reference your IoC container. As to where you put your factories, I guess that is up to you. It ultimately depends on who the primary consumers of those factories are. Some like to include factories in their API's, however I think that creates an undesirable coupling between the API, the Factory, and the implementations the factory creates. My preference is usually to locate the factories along side the consumers...which in your case, would be your controllers. Put them into their own projects, one with interfaces, the other with implementation – jrista Jul 01 '10 at 17:18
  • Just to clarify: Have 3 projects? 1 with IoC etc. 1 with domain stuff and factories and then 1 with the controllers etc (the actual MVC project)? Thanks! – TheCloudlessSky Jul 01 '10 at 20:26
  • I would actually have 4: one extra one to contain factory interfaces. The reason I would separate the interfaces (`IDataContextFactory`) from the implementation (`DataContextFactory`) is to maintain proper decoupling. You should bind to an interface, allowing the implementation of that interface to vary. In the case of production code, you would inject the concrete implementation. However, in the case of test code, for example, you would inject a mock version. Its best to keep our interfaces (or 'contracts') in separate assemblies from your implementation code. – jrista Jul 01 '10 at 20:54
  • I've updated the example to be more relevant to your situation. – jrista Jul 01 '10 at 20:57
  • -1 for abusing factories and violationg DRY. Instead take a look at the composition root Mark Seemann mentioned. http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx – Rookian Oct 14 '11 at 19:55
  • @Rookian: Before I just let that comment slide, you need to explain exactly how I am abusing factories and violating dry. I have not repeated anything in my code, and I am most certainly not "abusing" factories. – jrista Oct 15 '11 at 00:09
  • As for CompositionRoot. First, this has nothing to do with object graphs, as in data. Your building "the application", which is more of a functional dependency graph. I don't think you fully understand how ASP.NET works, or why it is necessary to inject dependencies into the constructors of each controller. Controllers are constructed for each request (or possibly pooled), they are rarely constructed once at the time the application starts and kept alive forever. – jrista Oct 15 '11 at 00:14
  • A .NET data context MUST be transient, and cannot be kept around longer than the duration of its use. A pooled controller may live considerably longer than that, thereby keeping a data context around far longer than it should live. Thus the use of factories to create instances on demand. The sole purpose of the factory is simply to abstract business code from an infrastructural component (the IoC container). The CompositionalRoot pattern does not seem to account for such constructs, however I have not violated it as the IoC wireup occurs in an application start event...once! – jrista Oct 15 '11 at 00:16
  • I also need to point out that a dogmatic adherence to "a single valid use" of an abstract concept like a "factory" is a dangerous attitude to hold when it comes to software development. Patterns are simply tools, and tools are what help us get the job done. Architecturally, if I choose to DEFINE a pattern called "factory" that follows specific rules and serves a specific purpose, that is a violation of nothing. The type of factory I have advocated here is not an abstract factory, it is a tool for dependency construction that abstracts. I called it a 'factory' as it produces functional objects. – jrista Oct 15 '11 at 00:20
  • @jrista What do you mean by a pooled controller? As far as I know the controller is always recreated per request. So the controller is transient. – Rookian Oct 15 '11 at 08:53
  • BTW Why is there an IDataContext AND Repositories? Why there are not only Repositories in the constructor of the controller? – Rookian Oct 15 '11 at 09:13
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/4288/discussion-between-rookian-and-jrista) – Rookian Oct 15 '11 at 10:47
3

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...
    }
}
TheCloudlessSky
  • 18,608
  • 15
  • 75
  • 116
Jamie Ide
  • 48,427
  • 16
  • 81
  • 117
2

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

mschaef
  • 1,620
  • 10
  • 12
2

I blogged about this very issue recently:

o3o
  • 1,094
  • 13
  • 23
Krzysztof Kozmic
  • 27,267
  • 12
  • 73
  • 115
  • Thanks for the links. So, it again comes down to using a factory. And from what I read, in order to instantiate the factory, you still have to have a reference to the IoC container, correct? – TheCloudlessSky Jul 01 '10 at 12:19
  • No you don't need any kind of reference to the container to get the factory, that's the whole point. – Krzysztof Kozmic Jul 01 '10 at 12:57
  • Ok so the factory has the reference to the container then? Where does the factory live? I understand how the factory is created, I'm just not sure where to put it. – TheCloudlessSky Jul 01 '10 at 16:03
  • I notice in your blog post you talk about one call to Resolve. I'm trying to implement my own IoC container (for learning) and was wondering *how* this can be achieved? – TheCloudlessSky Jul 01 '10 at 16:10
  • You also state that you make one Resolve call for the "root" (in my case the MVC Controller), where would it go? – TheCloudlessSky Jul 01 '10 at 16:16
  • See the documentation, it should answer some of your questions:http://stw.castleproject.org/Windsor.Typed-Factory-Facility.ashx You can also go and read the code - I'd argue that you will benefit more from it, than from writing your own simple container from scratch. – Krzysztof Kozmic Jul 01 '10 at 22:00
1

Have a second dependency injector to inject the first one, and have the first one inject the second one.

trejder
  • 17,148
  • 27
  • 124
  • 216
Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156