Towards Dev

A publication for sharing projects, ideas, codes, and new theories.

Follow publication

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

using xunit to test our code

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

Test Code

All Test passed😎

All code in this article you can find in Repo

thanks to DAVID GUIDA

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Published in Towards Dev

A publication for sharing projects, ideas, codes, and new theories.

Written by Amr elshaer

Software engineer | .Net ,C# ,Angular, Javascript

No responses yet

Write a response