问题描述
我正在查看依赖注入,可以看到好处,但是它创建的语法存在问题。我有这个示例
I am looking at depency injection, I can see the benefits but I am having problems with the syntax it creates. I have this example
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依赖什么来获得产品,我也觉得这会使我的代码更不可读。
because I feel the first alternative just feels unatural. I dont want to know what the BusinessProduct "depends" on to get the products, also I feel it makes my code more unreadable.
该方法是否有其他选择,因为我想保留创建对象的原始语法,但是我仍然希望在单元测试或
Is there any alternatives to this approach as I would like to keep my original syntax for creating objects but I would like to still be able to fake the dependencies when unit testing or is it this dependecy injection frameworks can do for me?
我正在用c#编写代码,但欢迎使用其他语言的替代方法
I am coding in c# but alternatives from other languages is welcome
推荐答案
我将工厂用于我的上下文并将其注入,如果提供的工厂为null,则提供合适的默认值。我这样做有两个原因。首先,我将数据上下文用作工作范围对象的一个单元,因此我需要能够在需要时创建它们,而不是一个对象。其次,我主要是使用DI来提高可测试性,而去耦仅是次要考虑因素。
I use a factory for my context and inject it, providing a suitable default if the provided factory is null. I do this for two reasons. First, I use the data context as a unit of work scoped object so I need to be able to create them when needed, not keep one around. Second, I'm primarily using DI to increase testability, with decoupling only a secondary consideration.
所以我的业务产品类如下:
So my business products class would look like:
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())
{
...
}
}
使工厂财产可以公开设置,并通过设置财产注入替代工厂。无论哪种方式,如果要保留null构造函数,都需要提供默认值。
An alternative to this would be to make the factory property publicly settable and inject an alternate factory by setting the property. Either way if you want to keep the null constructor, you'll need to provide a default.
这篇关于依赖注入替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!