sil*_*ire 5 .net c# asp.net-mvc inversion-of-control dryioc
我正在我的 Web 应用程序中试验 IoC,并希望根据最佳实践来做事。最近我发现了一个叫做 DryIoc 的 IoC 框架,它应该是小而快的。
我已经通读了这些示例,但似乎没有人指出我应该将容器放在哪里。
它应该驻留在控制器中吗?还是在 Global.asax 中?可能在别的地方?或者作为类中的静态变量?
如果有人能够指导我朝着正确的方向前进,最好是提供一些示例代码,我将不胜感激,因为我已经停滞不前并且不知道如何继续。
var container = new Container(); // Should obviously NOT be a local variable
container.Register<ISalesAgentRepository, SalesAgentRepository>(Reuse.Singleton);
Run Code Online (Sandbox Code Playgroud)
通常我会执行以下操作:
1 - 创建引导程序类
public static class Bootstrapper {
public static Container _container;
public void Bootstrap() {
var container = new Container;
// TODO: Register all types
_container = container;
}
public static T GetInstance<T>() {
return _container.Resolve<T>();
}
}
Run Code Online (Sandbox Code Playgroud)
2 - 在Application_Start方法中调用global.asax中的bootstrap方法:
protected void Application_Start() {
Bootstrapper.Bootstrap();
}
Run Code Online (Sandbox Code Playgroud)
并且永远不要直接在任何地方使用容器,您必须将其挂接到 MVC 生命周期中的某个位置,并且通常您使用的 DI 包可以为您完成此操作。
另请注意,我GetInstance<T>已向引导程序类添加了一个方法。该方法使得可以通过请求类型实例来直接使用容器。我添加了此方法,以便您知道这是可能的,但如果可能,请始终使用构造函数注入。