asp.net-mvc-3 - 如何访问 ASP.NET MVC3 Controller 中的 autofac 容器?

标签 asp.net-mvc-3 autofac

我想在 MVC Controller 中使用命名参数来解决依赖关系。如果我可以访问 Autofac 容器,我应该可以这样做:

var service = Container.Resolve<IService>(
    new NamedParameter("fileExtension", dupExt)
);

我不知道如何访问 AutoFac 容器。是否有对我可以使用的容器的全局引用,或者是否有另一种使用命名参数的方法?

最佳答案

我刚刚发现我可以使用 IComponentContext 来做同样的事情。您可以将 IComponentContext 的实例注入(inject) Controller 。

public class MyController : Controller
{
    private readonly IComponentContext _icoContext;

    public void MyController(IComponentContext icoContext)
    {
        _icoContext= icoContext;
    }

    public ActionResult Index()
    {
        var service = _icoContext.Resolve<IService>(
            new NamedParameter("ext", "txt")
        );
    }
}

在这个问题中,我找到了一些关于全局访问容器的好建议:
Autofac in web applications, where should I store the container for easy access?

我还在这里找到了如何访问全局依赖解析器:Global access to autofac dependency resolver in ASP.NET MVC3?

关于asp.net-mvc-3 - 如何访问 ASP.NET MVC3 Controller 中的 autofac 容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7838021/

相关文章:

c# - 仅为一个通用命令处理程序注册 Autofac 装饰器

c# - 在 WebApi 中使用 Autofac 进行 Hangfire

asp.net-mvc - MVC 3 _ViewStart,目的是什么?

c# - 解决条件依赖 autofac

Ajax 在 ASP MVC3 站点上返回 404 错误

c# - 如何使用c#在asp.net MVC3中创建一个文本文件

autofac - 使用 Autofac 进行 NancyFX 功能测试

c# - 使用 Autofac 注册通用接口(interface)和类

asp.net-mvc - MVC 3 和强类型 View

asp.net-mvc-3 - MVC3 要求 HTTPS 简单