我有一个由Simple.Data支持的类和一个类似ActiveRecord的接口,这个类的对象大多数时候是从静态方法创建的。我正在使用Castle Windsor迈出第一步,并希望在我的项目中使用它的Logging Facility(使用属性注入)。如何使用FindOrCreateByName而不是构造函数接收Person的实例?
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()
}
}
}
答案 0 :(得分:4)
将它们转换为实例方法。就是这样。
否则,您需要进入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>();
}