ASP.NET MVC 5暴露多个注射点,使您描述的功能。
最明确的是DependencyResolver
。默认的依赖关系解析器只是Activator.CreateInstance(controllerType)
,所以如果没有选择公共无参数的构造函数并且不会查找贪婪的构造函数,它会抛出一个错误。
但是,为您的用例增强此行为相当简单。
在全局配置,添加:
DependencyResolver.SetResolver(
type => {
if(type == typeof(AccountController))
{
var userManager = /* resolve the ApplicationUserManager...*/
var signInManager = /* resolve the ApplicationSignInManager...*/
return new AccountController(userManager, signInManager);
}
else
{
return Activator.CreateInstance(type)
}
},
type => Enumerable.Empty<object>()
);
该解决方案通过在代表而非IDependencyResolver
实现,但你可以很容易地提供一个强类型的解析器来代替。
您可能不会从这种方式获得您的IoC配置的任何实际价值,但应该指出,给定ASP.NET MVC 5框架完全有可能。最好的做法是引用NuGet包以将MVC 5与您的首选容器库集成,然后让它完成繁重的工作。我个人喜欢StructureMap(请查看this post的选定答案中的这种方式的示例)
DependencyResolver的源代码以及我在委托中使用的后备构造的基础可在https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.Mvc/DependencyResolver中找到。 cs – smartcaveman
“通过这种方式,您可能不会从您的IoC配置中获得任何实际价值”。不是每个人都会在这方面同意你的看法。有些人发现[Pure DI](http://blog.ploeh.dk/2014/06/10/pure-di/)是一个非常有价值的选择。 – Steven
@Steven - 我确定你是对的 - 几乎所有人都同意。伟大的博客,顺便说一句 - 我的声明实际上受到我从http://blog.ploeh.dk/2012/11/06/WhentouseaDIContainer/学到的东西的影响 – smartcaveman