Implementing factory pattern for dependency injection in .NET core
Published: 2021-03-23 15:53:40

ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving [Inversion of Control (IoC)](https://docs.microsoft.com/en-us/dotnet/architecture/modern-web-apps-azure/architectural-principles#dependency-inversion) between classes and their dependencies.

A *dependency* is an object that another object depends on. If there is a hardcoded dependency in the class i.e. the object is instantiated in the class, this could create some problems. In case there is a need to replace the dependency with another object, it would require the modification of the class. It also makes it difficult to unit test the class.

By using dependency injection we move the creation and binding of the dependent objects outside of the class that depends on them. Thus, solving the problems that we face with hardcoded dependency and making the classes loosely coupled.

###What is Factory Pattern?

The Factory Pattern was first introduced in the book “*Design Patterns: Elements of Reusable Object-Oriented Software*” by the “Gang of Four” (Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides).

The Factory Pattern is a Design Pattern which defines an interface for creating an object but lets the classes that have a dependency on the interface decide which class to instantiate. This abstracts the process of object generation so that the type of object to be instantiated can be determined at run-time by the class that want’s to instantiate the object. 

###When is Factory Pattern for DI required?

Factory Pattern is useful when there are multiple classes that implement an interface and there is a class that has a dependency on this interface. But this class will determine at run-time, based on user input, which type of object does it want to instantiate for that interface.

To understand this scenario further, let’s take an example of an interface called `IShape`.

{% gist https://gist.github.com/chaitanya-suvarna/7196804f1ec25ca664490ac24ec7522c %}

And we also have two classes called Cube and Sphere that implement `IShape`.

{% gist https://gist.github.com/chaitanya-suvarna/9e102fc9787461d58591654b1634e40e %}

Now, imagine we have a service class called `ShapeCalculationService` which has a dependency on `IShape`. It takes the input from user to choose either Cube or Sphere and based on the input it has to instantiate the `Cube` or `Sphere` object at runtime, how would that be possible?

The service class needs to use this corresponding Shape object to Get the input and display the SurfaceArea and Volume for the shape.

This scenario where multiple classes implement an interface and the object that needs to be instantiated is decided at runtime, is where Factory Pattern comes to use.

###How to implement Factory Pattern for DI?

Continuing with above example, we will try to implement factory pattern in this scenario.
To abstract the instantiation of the correct Shape object at runtime, we will create a `ShapeFactory` class who’s responsibility is to resolve which concrete class is required to be instantiated for a given selection by user.

{% gist https://gist.github.com/chaitanya-suvarna/d0921dd0acc38e148922f6d38ea717d3 %}

Here you can see that the `ShapeFactory` class has a dependency on `IServiceProvider` so that `ShapeFactory` only resolves which concrete class needs to be instantiated but should ask the built-in service container of .Net core to get the instance and resolve its dependencies.

This is because we want to rely on **IoC container of .Net core** to resolve our dependencies and don’t want to make changes in out factory every single time a new dependency is introduced in either of `Cube` or `Sphere` classes.
This further **decouples** the code and makes it easier to manage.

The place where you setup the ServiceCollection for your project should look like below so that the DI of .Net core could figure out the required dependencies by either of the service and could resolve them at run time.

In my example, since this is a simple console application, this code resides in `Program.cs`

{% gist https://gist.github.com/chaitanya-suvarna/2a7742177e2ee09bcc82fdb4604388ee %}

Finally, I’d also like you to see the actual `ShapeCalculationService` that takes an input from the user and uses `ShapeFactory` to get the `Shape` class at runtime which is the used to display the surface area and the volume.

{% gist https://gist.github.com/chaitanya-suvarna/d0fef4ed96038e57e94f030f03d8ec5e %}

###Conclusion

Thus we have seen how we can inject a factory to get total control of creation of our dependencies at runtime, while still using .Net core’s IoC container to resolve our dependencies.

If you are like me, who needs a small yet complete demo solution to clearly understand how this works, I have created a demo project in my github repository which would help you understand this better.
You can have a look at it here : [DotNetCoreFactoryPattern](https://github.com/chaitanya-suvarna/DotNetCoreFactoryPattern)

I hope you found this interesting. Thanks for reading!