依赖注入的最佳实践

tjh*_*ack 9 c# asp.net-mvc dependency-injection ninject asp.net-mvc-4

我正在使用MVC 4在ASP.net中创建一个新项目.

我想使用设置依赖注入Ninject.但在我开始设置依赖注入之前,最好的做法是什么?

目前我在webproject中有一个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>();
    }

}
Run Code Online (Sandbox Code Playgroud)

然后在我的控制器中,我使用GetImplementation方法来使用确切的require依赖项,而不是在应用程序启动时注册所有.

控制器的示例代码:

Public ActionResult Get (int id)
{
    var repository = Binder.GetImplementation<IDocuments>();

    // do some stuff with the repository here
}
Run Code Online (Sandbox Code Playgroud)

不确定这是不是一个好方法?任何建议都会很好.

Wik*_*hla 16

你现在拥有的是Service Locator反模式的一个例子.Google已经多次讨论了更多细节.

简而言之,而不是依靠服务定位器

public class SomeController 
{
  public ActionResult Get (int id)
  {
      var repository = Binder.GetImplementation<IDocuments>();

      // do some stuff with the repository here
  }
}
Run Code Online (Sandbox Code Playgroud)

你应该将你的服务注入到客户端类中(依赖于构造函数注入)

public class SomeController 
{
  private IDocuments documentService { get; set; }      

  public SomeController( IDocuments documentService ) 
  {
    this.documentService = documentService;
  } 

  public ActionResult Get (int id)
  {
      var repository = documentService; 

      // do some stuff with the repository here
  }
}
Run Code Online (Sandbox Code Playgroud)

在这种特定情况下,您可以设置控制器工厂以使用IoC容器来解析控制器.