这是正确的有2个构造器,一个用于依赖注入,另一种解决注射? [英] It's correct to have 2 constructors, one for Dependency Injection and the other one Resolving the injection?
本文介绍了这是正确的有2个构造器,一个用于依赖注入,另一种解决注射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个构造函数在我的课:
I have 2 constructor in my class:
public class VuelingCacheWebServices : IVuelingCacheWebService
{
public IVuelingCache apiConnector { get; set; }
public VuelingCacheWebServices(IVuelingCache ApiConnector)
{
apiConnector = ApiConnector;
}
public VuelingCacheWebServices()
: this(new VuelingCache())
{ }
}
正如你所看到的,我已经视IVuelingCache一个构造函数,并且创建一个实例传递到第一个构造函数默认构造函数。这是对的吗?这样,我摆脱了工厂类。
As you can see, I have one constructor depending on IVuelingCache and a default constructor that creates an instance to pass to the first constructor. Is it correct? in this way i get rid of the Factory class.
推荐答案
这是确保你有一个有效的实例的一种方法< 。code> IVuelingCache - 这种模式有一个名字 - 穷人的依赖注入
This is one way to ensure that you have a valid instance of IVuelingCache
- this pattern has a name - poor man's dependency injection.
的有些的看的这个作为一个反模式,因为你是硬编码默认的实施到你的代码。
Some see this as an anti-pattern, as you are hard coding the "default" implementation into your code.
这篇关于这是正确的有2个构造器,一个用于依赖注入,另一种解决注射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文