Improving Factory Pattern using DI in .Net
In this article, we do not focus on Factory Pattern but on how to improve Factory Pattern using Dependency Injection in.Net 5.
The Factory Pattern is one of the Creational patterns explained in the amazing Gang-of-Four book that every software engineer should have next to their bed. Quoting:
“Define an interface for creating an object, but let subclasses decide which class to instantiate. The Factory method lets a class defer instantiation it uses to subclasses.”
Let’s dive into a simple example

We basically define a common interface IDocumentProcessor and defer to our IDocumentProcessorFactory providing the right instance based on some input parameter.
Plain and easy.
Now, what’s the problem with this? Dependencies. This Factory assumes that every IDocumentProcessor implementation takes no dependencies and has a very simple instantiation mechanism.
but what if our subclasses depend on other classes like this






Now, this works fine and potentially solves all your problems , but we can benefit from dependency injection and improve our code by making lookup Dictionary and inject it in configureServices like this:-

update DocumentProcessor Factory and update ConfigureServices



All Test passed😎
All code in this article you can find in Repo
thanks to DAVID GUIDA