Castle Windsor 与静态方法
Castle Windsor vs. static methods
我有一个 class 由 Simple.Data 支持,带有类似 ActiveRecord 的接口,这个 class 的对象大部分时间都是从静态方法创建的。我正在使用 Castle Windsor 迈出第一步,并希望在我的项目中使用它的日志记录工具(使用 属性 注入)。我如何使用 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()
}
}
}
将它们变成实例方法。就这些了。
否则,您需要陷入 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>();
}
我有一个 class 由 Simple.Data 支持,带有类似 ActiveRecord 的接口,这个 class 的对象大部分时间都是从静态方法创建的。我正在使用 Castle Windsor 迈出第一步,并希望在我的项目中使用它的日志记录工具(使用 属性 注入)。我如何使用 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()
}
}
}
将它们变成实例方法。就这些了。
否则,您需要陷入 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>();
}