I like Constructor injection for dependency injection. It forces a clear declaration of concerns from a type and helps with testability.
I like Constructor injection, in most places...
Logging as an example where I do not like it. If I have a base class from which many other classes inherit, and I want all of those classes to use an instance of my ILogger (or whatever), and I don't want a static factory (Logger.Instance)...I don't want to have to declare a constructor on every sub-class that takes an ILogger.
So, I could have my base class declare the logger as a Property and have it injected that way
public class MyBaseClass
{
public ILogger Logger { get; set; }
}
...but
- That doesn't assure me that Logger actually gets injected and is not null.
- I don't like having ILogger with a public set
So...what other options do I have? (I'm using Castle Windsor).
I've contemplated making an interface
public interface IInitializable<T>
{
void Initialize(T instance);
}
public class MyBaseClass : IInitializable<ILogger>, ...could have other IInitializables too...
{
protected ILogger Logger { get; private set; }
public void Initialize(ILogger instance)
{
Logger = instance;
}
}
Then having a facility on my container that automatically calls all implementations of IInitializable<T>
upon type construction...
But I'm wondering what other peoples' thoughts are before I go that route...