2012-10-23 128 views
2

我有这样的构造函数:依赖注入重构

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; 

    } 

当然,这是行不通的。任何人有任何建议,我可以重构此代码? 我需要这样做才能在单元测试中模拟Section类型的对象。我们正在使用FakeItEasy测试框架。

+1

你在你的第二个例子中有重复的代码 - 你不需要在第一个构造函数的内容行。除此之外,它不是一个完全依赖注入的解决方案,但我不明白为什么代码会失败。 –

+0

是的,我的不好,我不使用第一个ctor中的内容行。当我复制粘贴时,我很匆忙。所以第一个ctor不包含任何东西。我需要一个默认的构造函数,以便能够伪造一个类型为Section的对象来进行单元测试。 – IonutC

回答

1

一个问题是你的第一个构造函数,没有参数的构造函数委托给第二个构造函数。换句话说,第二个将被第一个与this()声明中的参数一起调用。然而,第一个也包含_tabs_sections的setter,这是冗余的。它应该是这样的:

public Section() 
    : this(new TabCollection(this), new SubSectionCollection(this)) 
{ } 

public Section(TabCollection tabCollection, IList<ISection> sections) 
{ 
    _tabs = tabCollection; 
    _sections = sections; 
} 

这是构造函数链,不过,这是在依赖注入中使用的技术。这是你问的吗?

+0

是的,你是对的。我需要使用这种链接和依赖注入才能伪造Section类型的对象。我知道我应该使用tabcollection和SubSectionCollection的接口,但这不是重点。问题是,因为我在实例化TabCollection和SubSectionCollection时没有词“this”,所以我无法进行链接。 – IonutC

1

依赖注入并不一定意味着你的类在构造时不能实例化它的某些字段/属性。我通常使用构造函数注入“服务”,而不是一组子对象。

但是,我不知道代码的所有细节,因此您可能需要使用Factory模式。像SectionFactory东西可能使这里感觉......

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); 
    } 
}