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

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

问题描述

我对使用 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 调用,并将其绑定到您的容器.这些额外的依赖破坏了使用 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>();
    }
}

我将容器包装在这样的 Container 类中.它将自己添加到构造函数中的包装容器中.现在需要容器的类可以注入 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)

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

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