【问题标题】:Castle Windsor vs. static methods温莎城堡与静态方法
【发布时间】:2019-08-09 00:56:43
【问题描述】:

我有一个由 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()
        }
    }

}

【问题讨论】:

    标签: c# castle-windsor


    【解决方案1】:

    把它们变成实例方法。就是这样。

    否则,您将需要落入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>();
    }
    

    【讨论】:

    • 这很有意义
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多