Developers are usually encouraged to do dependency injection with interfaces. Some developers don’t know that they can do dependency injection with delegates, and there are good reasons to do this. By Christian Findlay.
Moreover, developers can use delegates with modern IoC containers like ASP.NET Core’s IoC container, mock delegates, and verify calls. It is good practice and should be encouraged. Let’s have a look at why.
Firstly, let’s focus on the interface segregation principle. It’s one of the SOLID principles. It essentially means that you should minimize the number of members on an interface. It sometimes leads to an interesting situation where interfaces end up with only one method.
The article then dives into:
- Why use Delegates instead of Interfaces?
- Dependency Injection with Delegates
- Mocking Delegates with Moq
- Delegates with IoC Containers
- What if the delegate code needs extra dependencies?
- Drawbacks Of Delegates
At their heart, IoC containers are collections keyed by type. We normally key the collection by interface types, but delegates are also types, and we can key the collection with delegates instead of interfaces.
All source code for this article can be found in GitHub repository. But, be careful of scenarios with generic types. You shouldn’t alter the fundamental design of your code to fit delegates. Rather delegates should be a compliment to your existing code design. Nice one![Read More]