Improving Factory Pattern using keyed services in .Net 8

Amr elshaer
3 min readApr 24, 2024

--

This article is an updated version of the last story Improving Factory Pattern using DI in .Net, you read first in, we started with a strategy of many types of processing files like PDF, ODT, and Doc types and using factory method with dependency injection to inject all types in startup class, before we start, I recommend to read first about keyed services by Andrew Lock give us a simple example

this is the contract class INotificationService and has many types like SMS, email, push

now we can inject our services with key

and in the wrapper or class that wants to consume each type we can detect the type we need to inject like this

This is all very good and nice in the case of compile time you know in each class what service need to inject , but in most cases in the complex systems we need to determine the class want to inject at runtime like getting a type of Order and according to the order type we need a specific service, so you can’t benefit directly from this keyed services, you need to add factory class and take type and based of type return the service, so in the last article we discuss to make this but with the old version, now we can benefit from keyed services like this, first I will replace type by string with enum

second I update the dependency injection of the factory class and injection of types.

update factory class

all source code can be seen in the new branch keyed-services.

--

--

Amr elshaer
Amr elshaer

Written by Amr elshaer

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

Responses (1)