加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – 如何在ASP.NET MVC3控制器中访问autofac容器?

发布时间:2020-12-16 00:40:23 所属栏目:asp.Net 来源:网络整理
导读:我想在MVC控制器中使用named参数来解析依赖关系。如果我可以访问Autofac容器,我应该可以这样做: var service = Container.ResolveIService( new NamedParameter("fileExtension",dupExt)); 我找不到如何访问AutoFac容器。有没有对我可以使用的容器的全局引
我想在MVC控制器中使用named参数来解析依赖关系。如果我可以访问Autofac容器,我应该可以这样做:
var service = Container.Resolve<IService>(
    new NamedParameter("fileExtension",dupExt)
);

我找不到如何访问AutoFac容器。有没有对我可以使用的容器的全局引用,还是有另一种使用命名参数的方式?

解决方法

我刚刚发现我可以使用IComponentContext做同样的事情。您可以将IComponentContext的实例注入到控制器中。
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?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读