Dependency Injection and events by Mark Seemann
Overview of articles about Dependency Injection and events.
One of my readers, Kenny Pflug, asks me about subscribing to events in the constructor of a class using Constructor Injection:
I want to register to a plain old .NET event of a dependency that is supplied via constructor injection. I read your book "DI in .NET" and in it you mention that injection constructors should be simple and not perform any other work than guarding for null values and assigning the dependencies to (read-only) fields. I also read on your blog that this is only a pattern and might be broken gently if the need would arise.
[...] do you know and prefer any patterns to solve this "registering to events of dependencies in a constructor" problem?
In short, I think that it's a code smell if a design requires you to subscribe to an event in the constructor; it's a smell that the dependency chain is slightly inverted. Inversion of Inversion of Control - how about that?
In the next series of posts, I'll attempt to provide various perspectives on this situation, starting with the original context.
- DI and events: Constructor Subscription.
- DI and events: Third-party Connect.
- DI and events: Reactive Extensions.
- DI and events: Composition.
In summary, it's probably not going to be a big problem if you subscribe to an event in a constructor, but it's a code smell, because it betrays a design issue.