1

我对依赖注入相当陌生,我正在寻找一些关于最佳实践的建议。抱歉,之前是否有人问过这个问题,但我还没有找到好的解决方案。

假设我有一个 MVC4 Web 应用程序和一个单独的业务层。MVC 应用程序已经使用 Ninject NuGet 包设置,所以我有 NinjectWebCommon,它工作正常。

我的问题是:当我需要在其他层设置依赖项时,如何使用 Ninject?

假设我有这个存储库:

public class WidgetRepository : IWidgetRepository
{
    // using an entity framework db context.
    WidgetDbContext context = new WidgetDbContext();

    public IQueryable<Widget> Widgets
    {
        get
        {
            return context.Widgets;
        }
    }
}

存储库返回的每个小部件都需要使用我需要注入的计算器对象执行计算:

public class Widget
{
    // how can I get Ninject to inject a calculator object 
    // when Widgets are loaded form the database?

    public ICalculator calculator;

    public int MyValue { get; set; }

    public int CalculateSomething
    {
        get
        {
            return calculator.Calculate(MyValue);
        }
    }
}

当在 MVC Web 应用程序中设置了 Ninject 但在业务层中创建了 Widget 对象时,将 ICalculator 注入每个 Widget 实例的最佳实践是什么?

4

2 回答 2

1

防止在实体中进行构造函数注入或属性注入。您应该:

  1. 让服务层调用Widget上的计算,像这样:

    var widget = this.repository.GetById(wigditId);
    var value = this.calculator.Calculate(widget.MyValue);
    
  2. 或者在您的实体中使用构造函数注入:

    var widget = this.repository.GetById(wigditId);
    var value = widget.CalculateSomething(this.calculator);
    

关于这一点已经写了很多。例如,看看这些文章:

于 2013-09-18T14:50:47.173 回答
0

如果 Widget 和 ICalculator 在同一个项目中,只需使用构造函数注入即可:

public class Widget
{
    public Widget(ICalculator calculator)
    {
      _calculator = calculator;
    }

    private ICalculator _calculator;

    public int MyValue { get; set; }

    public int CalculateSomething
    {
        get
        {
            return _calculator.Calculate(MyValue);
        }
    }
}

在 NinjectWebCommon 中,您需要注册您的 ICalculator 实现,如下所示:

private static void RegisterServices(IKernel kernel)
{
  kernel.Bind<ICalculator>()
              .To<Calculator>();
}
于 2013-09-18T13:58:18.570 回答