2016-09-05 73 views
1

我有一個由類似於ActiveRecord接口的Simple.Data支持的類,這個類的對象大多數情況下都是通過靜態方法創建的。我正在與Castle Windsor一起邁出第一步,並希望在我的項目中使用它的Logging Facility(使用屬性注入)。我如何使用FindOrCreateByName而不是構造函數接收Person的實例?Castle Windsor與靜態方法

public class Person 
{ 
    public ILogger Logger { get; set; } 
    public static Person FindByName(string name) 
    { } 
    public static Person FindOrCreateByName(string name) 
    { } 
    public void DoSomething() { } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     using (var container = new WindsorContainer()) 
     { 
      container.Install(FromAssembly.This()); 
      // Create Person from FindOrCreateBy() 
     } 
    } 

} 

回答

3

把它們變成實例方法。就這樣。

否則,您必須落入service locator anti-pattern

public static Person FindByName(string name) 
{ 
    // You're coupling your implementation to how dependencies are resolved, 
    // while you don't want this at all, because you won't be able to test your 
    // code without configuring the inversion of control container. In other 
    // words, it wouldn't be an unit test, but an integration test! 
    ILogger logger = Container.Resolve<ILogger>(); 
} 
+0

這非常有意義 – Sumone