依赖注入最佳实践

9

我正在使用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
}

不确定这是否是一个好的方法?有什么建议吗?


4
需要稍微加点代码吗? - BenjaminPaul
1
@Wiktors下面的答案是正确的方法。尽量使用构造函数注入。只有在某种原因下无法设置完整的依赖链时,才使用SL反模式。 - Nick Ryan
3个回答

16

您现在所拥有的是服务定位器反模式的一个例子。搜索更多细节,因为它已经被讨论了很多次。

简而言之,不要依赖于服务定位器。

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

      // do some stuff with the repository here
  }
}

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

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
  }
}
在这种情况下,您可以设置控制器工厂,以使用您的IoC容器解析您的控制器。

4

0

您在控制器内部连接到了 Binder 类的实例。这将导致您的类不可重用,必须进行重构。因为获取 IDocuments 实现的正确实例并非控制器的职责。

必须使用一些外部依赖解析器(例如 Ninject)进行构造函数注入或属性注入。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接