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.

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.



Wish to comment?

You can add a comment to this post by sending me a pull request. Alternatively, you can discuss this post on Twitter or somewhere else with a permalink. Ping me with the link, and I may respond.

Published

Friday, 06 September 2013 08:38:00 UTC

Tags



"Our team wholeheartedly endorses Mark. His expert service provides tremendous value."
Hire me!
Published: Friday, 06 September 2013 08:38:00 UTC