Reputation: 448
Simple case: I have an interface for logging messages, like this:
public interface ILogger
{
void Log(string message);
}
And maybe three different classes implement this interface.
Now, I could write in one place, line for DI, something like:
kernel.Bind<ILogger>().To<ConsoleLogger>();
My question is, how use that interface in many classes, but without injecting everyone via constructor. Because we can have so many different interfaces we want use, and declaration on that class constructor can be messy.
Upvotes: 3
Views: 475
Reputation: 34309
Having too many injected items in your constructor is a code smell. This normally means your class is doing more than one role. The single responsiblity principle says that each class should have only one purpose which is entirely encapsulated in the class.
Upvotes: 5
Reputation: 1714
While what @LukeMcGregor says it's true in general, a Logger looks like a cross-cutting concern, and could also be solved via AOP if you don't want to pollute every constructor with an ILogger. Ninject seems to support AOP via ninject.extensions.interception.
Upvotes: 1
Reputation: 42495
In dependency injection, using property injection outside of legacy scenarios is considered poor form. Injecting a value via properties suggests its optional, and thus not really a dependency.
If you have a type that has lots and lots of constructor dependencies, that may suggest you need to do some refactoring. Perhaps some types are used together and can be refactored into their own component. Either way, if you are using an IoC framework such as Ninject, does it really matter how many constructor parameters a type takes? The container will do the injection for you regardless.
Upvotes: 2
Reputation: 8513
You can implement an ILogger Logger { get; set;}
property in the classes and use the property injection feature that most IoC containers support.
Upvotes: 0