可以說我有在C#下面的代碼:注入第三方類,而無需創建工廠
public class AppleTree
{
public AppleTree()
{
}
public string GetApple
{
return new Fruit("Apple").ToString();
}
}
,其中水果是不具備的接口第三方類。
我想創建一個AppleTree類的單元測試,但我不想運行Fruit類。相反,我想注入Fruit類,以便在測試中嘲笑它。
我應該怎麼做呢?我可以創建一個工廠,創建的蘋果,然後在接口添加到該工廠,如:
public class FruitFactory : IFruitFactory
{
Fruit CreateApple()
{
return new Fruit("Apple");
}
}
現在我可以注入IFruitFactory到蘋果樹和使用CreateApple,而不是新的果實爲:
public class AppleTree
{
private readonly IFruitFactory _fruitFactory;
public AppleTree(IFruitFactory fruitFactory)
{
_fruitFactory = fruitFactory
}
public string GetApple
{
return _fruitFactory.CreateApple().ToString();
}
}
現在我的問題是:有沒有創建工廠這樣做的好方法?例如,我可以用某種方式使用像Ninject這樣的依賴注入器類的框架嗎?
有趣的解決方案,我會試試 有一個博客文章作者解釋它[這裏](http://www.planetgeek.ch/2011/12/31/ ninject-extensions-factory-introduction /) – Martin
祝你好運(順便說一下,博客文章是我鏈接到的wiki文章的來源材料 - 並記住它的wiki,所以任何讓你困惑的東西或你擁有的任何好點子,都要編輯一些東西!) –