我想在 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/