我正在使用MVC 4在ASP.net中创建一个新项目。
我想使用Ninject
设置依赖注入。但在继续之前,设置依赖注入的最佳实践是什么?
目前,在Web项目中设置了一个Binder类,该类将引用解决方案中的数据项目。
Binder类如下所示:
Public static class Binder
{
static Ninject.IKernel _kernel;
static Binder()
{
_kernel = new Ninject.StandardKernel();
_kernel.Bind<IConfig>().To<AppSettingsConfig>();
_kernel.Bind<IDocuments>().To<DocumentsClass.Documents>();
}
public static T GetImplementation<T>()
{
return _kernel.Get<T>();
}
}
然后在我的控制器中,我使用GetImplementation方法来使用精确的所需依赖项,而不是在应用程序启动时注册所有依赖项。
控制器的示例代码:
Public ActionResult Get (int id)
{
var repository = Binder.GetImplementation<IDocuments>();
// do some stuff with the repository here
}
不确定这是否是一个好的方法?有什么建议吗?