Autofac在Web应用程序,我应该在哪里存储以便于访问容器? [英] Autofac in web applications, where should I store the container for easy access?

查看:165
本文介绍了Autofac在Web应用程序,我应该在哪里存储以便于访问容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是pretty初次使用Autofac和一件事,我的文档中思念和例子是如何可以很容易地得到来自Web应用程序不同的地方配置容器。

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 in a web application.

我知道我可以使用Autofac控制器厂自动解决了控制器构造函数注入依赖关系,但如何对其他的东西,你可能需要解决尚未注入。

I know I can use the Autofac controller factory to automatically resolve constructor injected dependencies for controllers, but how about the other stuff you might need to resolve that is not injected yet.

时有一个明显的模式,我不是这个知道的?

Is there an obvious pattern I am not aware of for this?

感谢您!

推荐答案

首先尽量不要过度使用IoC容器。其为接线向上控制器,视图和服务,但是需要在运行时被创建的对象极大应由工厂对象,而不是由容器创建。否则,你得到Container.Resolve呼吁通过你的code,其直接连接到你的容器。这些额外的依赖打败使用的IoC的目的。在大多数情况下,我可以只在我的应用程序的顶级解决一个或两个依赖得到。那么IoC容器将递归解决大多数的依赖性。

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<IContainer>(this);
    }

    public T Resolve<T>()
    {
        return container.Resolve<T>();
    }
}

我在包装容器类这样的容器。它增加了自己在构造函数中包装的容器。现在需要的容器类可以有一个注入的IContainer。 (这个例子是温莎城堡,但大概可以适应AutoFac)

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)

这篇关于Autofac在Web应用程序,我应该在哪里存储以便于访问容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆