Autofac in web applications, where should I store the container for easy access?

前端 未结 5 1055
难免孤独
难免孤独 2020-12-08 23:16

I\'m still pretty new to using Autofac and one thing I miss in the documentation and examples is how to make it easy to get to the configured container from different places

5条回答
  •  执笔经年
    2020-12-08 23:37

    First of all try not to overuse the IoC container. Its great for "wiring up" controllers, views and services but objects that need to be created during runtime should be created by factory objects and not by the container. Otherwise you get Container.Resolve calls all through your code, tying it to your container. These extra dependencies defeat the purpose of using IoC. In most cases I can get by only resolving one or two dependencies at the top level of my application. The IoC container will then recursively resolve most dependencies.

    When I need the container elsewhere in my program here's a trick I often use.

    public class Container : IContainer
    {
        readonly IWindsorContainer container;
    
        public Container()
        {
            // Initialize container
            container = new WindsorContainer(new XmlInterpreter(new FileResource("castle.xml")));
    
            // Register yourself
            container.Kernel.AddComponentInstance(this);
        }
    
        public T Resolve()
        {
            return container.Resolve();
        }
    }
    

    I wrap the container in a Container class like this. It adds itself to the wrapped container in the constructor. Now classes that need the container can have an IContainer injected. (the example is for Castle Windsor but it can probably be adapted for AutoFac)

提交回复
热议问题