c# - 依赖注入(inject)替代方案

标签 c# dependency-injection

我正在研究依赖注入(inject),我可以看到它的好处,但我在使用它创建的语法时遇到了问题。我有这个例子

public class BusinessProducts
{
   IDataContext _dx;

   BusinessProducts(IDataContext dx)
   {
      _dx = dx;
   }

   public List<Product> GetProducts()
   {
    return dx.GetProducts();
   }
}

问题是我不想写

BusinessProducts bp = new BusinessProducts(dataContextImplementation);

我会继续写

BusinessProducts bp = new BusinessProducts();

因为我觉得第一种选择感觉不自然。我不想知道 BusinessProduct “依赖”什么来获得产品,而且我觉得这让我的代码更难读。

这种方法是否有任何替代方法,因为我想保留我创建对象的原始语法,但我仍然希望在单元测试时能够伪造依赖关系,或者这种依赖注入(inject)框架可以为我做吗?

我正在用 c# 编写代码,但欢迎使用其他语言的替代品

最佳答案

我为我的上下文使用工厂并注入(inject)它,如果提供的工厂为空,则提供合适的默认值。我这样做有两个原因。首先,我将数据上下文用作工作范围对象的一个​​单元,因此我需要能够在需要时创建它们,而不是保留一个。其次,我主要使用 DI 来提高可测试性,解耦只是次要考虑因素。

所以我的业务产品类看起来像:

public class BusinessProducts
{
     private IDataContextFactory DataContextFactory { get; set; }  // my interface

     public BusinessProducts() : this(null) {}

     public BusinessProducts( IDataContextFactory factory )
     {
          this.DataContext = factory ?? new BusinessProductsDataContextFactory();
     }

     public void DoSomething()
     {
          using (DataContext dc = this.DataContextFactory().CreateDataContext())
          {
             ...
          }
     }

另一种方法是使工厂属性可公开设置,并通过设置该属性来注入(inject)备用工厂。无论哪种方式,如果您想保留 null 构造函数,您都需要提供默认值。

关于c# - 依赖注入(inject)替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/359122/

相关文章:

dependency-injection - 在 TopShelf 和 Quartz 范围问题中使用 Microsoft DependencyInjection

c# - 注册类时依赖注入(inject)错误 : Unable to resolve service for type while attempting to activate,

c# - 使用文件 URL 启动 Edge

c# - 列表的 Find(s) 方法在 C# 中的工作原理

php - 交响乐团 3 : can't overwrite repository

scala - 无法使用 macwire 注入(inject) Play WS 或 WSClient

c# - 等效于 Xamarin 中 NSData 的 NSString.CreateNative()

c# - 等待单个任务从 List<Task<..>> 中更干净地失败,可能使用 LINQ?

c# - 是否有 C# 方法重载参数排序约定?

scala - 没有类的 Scala 依赖注入(inject)