C# 依赖注入重构
我有一个问题:C# 依赖注入重构,c#,asp.net,asp.net-mvc,c#-4.0,fakeiteasy,C#,Asp.net,Asp.net Mvc,C# 4.0,Fakeiteasy,我有一个问题: public Section() { _tabs = new TabCollection(this); _sections = new SubSectionCollection(this); } 我想得到这样的东西: public Section() : this(new TabCollection(this), new SubSectionCollection(this)) { }
public Section()
{
_tabs = new TabCollection(this);
_sections = new SubSectionCollection(this);
}
我想得到这样的东西:
public Section()
: this(new TabCollection(this), new SubSectionCollection(this))
{
}
public Section(TabCollection tabCollection, IList<ISection> sections)
{
_tabs = tabCollection;
_sections = sections;
}
public Section()
: this(new TabCollection(this), new SubSectionCollection(this))
{ }
public Section(TabCollection tabCollection, IList<ISection> sections)
{
_tabs = tabCollection;
_sections = sections;
}
公共部分()
:this(新TabCollection(this)、新SubSectionCollection(this))
{
}
公共部分(TabCollection TabCollection,IList部分)
{
_tabs=tabCollection;
_截面=截面;
}
这当然行不通。有人对我如何重构这段代码有什么建议吗?
我需要这样做,以便能够在单元测试中模拟Section类型的对象。我们正在使用Fakeitesy测试框架。一个问题是,您的第一个构造函数(没有参数的构造函数)将委托给第二个构造函数。换句话说,第二个将由第一个调用,参数在
this()
语句中。但是,第一个还包含\u选项卡
和\u节
的setter,这是多余的。应该是这样的:
public Section()
: this(new TabCollection(this), new SubSectionCollection(this))
{
}
public Section(TabCollection tabCollection, IList<ISection> sections)
{
_tabs = tabCollection;
_sections = sections;
}
public Section()
: this(new TabCollection(this), new SubSectionCollection(this))
{ }
public Section(TabCollection tabCollection, IList<ISection> sections)
{
_tabs = tabCollection;
_sections = sections;
}
公共部分()
:this(新TabCollection(this)、新SubSectionCollection(this))
{ }
公共部分(TabCollection TabCollection,IList部分)
{
_tabs=tabCollection;
_截面=截面;
}
不过,这是构造函数链接,这是依赖项注入中使用的一种技术。这就是你要问的吗?依赖注入并不一定意味着你的类在构建时不能实例化它的一些字段/属性。我通常将构造函数注入用于“服务”,而不是子对象的集合 但是,我不知道代码的所有细节,因此您可能希望使用工厂模式。像工厂这样的东西在这里可能有意义
public class Section
{
internal Section(TabCollection tabColl, SectionCollection subSections)
{
// check for null, etc.
// do whatever you need to do to finish construction
tabColl.Parent = this;
subSections.Parent = this;
}
}
public class SectionFactory : ISectionFactory
{
public Section Create()
{
var tabs = new TabCollection();
var subs = new SectionCollection();
return new Section(tabs, subs);
}
}
在第二个示例中,您有重复的代码-您不需要第一个构造函数中的内容行。除此之外,它不是一个完全依赖注入的解决方案,但我不明白为什么代码会失败。是的,我的错,我没有在第一个ctor中使用内容行。复制粘贴时我很匆忙。所以第一个ctor不包含任何内容。我需要一个默认构造函数,以便能够为单元测试伪造Section类型的对象。是的,你是对的。我需要使用这个链接和依赖项注入,以便能够伪造Section类型的对象。我知道我应该为tabcollection和SubSectionCollection使用接口,但这不是重点。问题是,因为我在实例化TabCollection和SubSectionCollection时使用了“this”这个词,所以我无法进行链接。