Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put the Container?

I'm experimenting with IoC in my Web App and would like to do things according to best practices. Recently I discovered an IoC framework called DryIoc which is supposed to be small and fast.

I've read through the examples but none seem to point out where I should put the container itself.

Should it reside in the controller? Or in Global.asax? Someplace else maybe? Or perhaps as a static variable in a class?

I'd appreciate if someone would be able to guide me in the right direction, preferrably with some sample code, as I've stalled and don't got a clue on how to continue.

var container = new Container();   // Should obviously NOT be a local variable

container.Register<ISalesAgentRepository, SalesAgentRepository>(Reuse.Singleton);
like image 338
silkfire Avatar asked Oct 18 '22 13:10

silkfire


1 Answers

Usually I do the following:

1 - Create a bootstrapper class

public static class Bootstrapper {
    public static Container _container;
    public void Bootstrap() {
        var container = new Container;
        // TODO: Register all types
        _container = container;
    }
    public static T GetInstance<T>() {
        return _container.Resolve<T>();
    }
}

2 - Call the bootstrap method in the global.asax, in the Application_Start method:

protected void Application_Start() {
    Bootstrapper.Bootstrap();
}

And never use the container anywhere directly, you have to hook it somewhere in the MVC lifecycle, and usually the DI package you use can do this for you.

Also note that I've added a GetInstance<T> method to the bootstrapper-class. This method is what makes it possible to use the container directly by requesting instances of types. I've added this method so you know it is possible, but always use constructor-injection if possible.

like image 100
Maarten Avatar answered Oct 21 '22 06:10

Maarten