2
votes

I have a class backed by Simple.Data with an ActiveRecord like interface, objects of this class are created from static methods most of the time. I'm making my first steps with Castle Windsor and would like to use it's Logging Facility (using property injection) within my project. How can i receive an instance of Person using FindOrCreateByName instead of the constructor?

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()
        }
    }

}
1

1 Answers

4
votes

Turn them into instance methods. That's all.

Otherwise, you'll need to fall into the 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>();
}