Replacing Switch Statements with the Factory Pattern in C#

Milan Jovanović

Milan Jovanović

32,104 views

My annual spring sale is now live. Check it out: https://www.milanjovanovic.tech/sprin...
Get the source code for this video here → https://the-dotnet-weekly.kit.com/fac...

Want to master Clean Architecture? Go here: https://dub.sh/clean-architecture
Want to master Modular Monoliths? Go here: https://dub.sh/modular-monolith

Join the .NET Architects Club: https://www.skool.com/mj-tech-communi...
Get the 2026 .NET Developer roadmap here → https://the-dotnet-weekly.ck.page/202...

What happens when one service becomes responsible for creating dependencies, reading configuration, selecting implementations, and executing business logic?

You end up with code that is harder to test, harder to extend, and harder to maintain.

In this tutorial, I’ll refactor a messy NotificationService that supports email, SMS, and Slack notifications using the Factory Pattern in .NET.

We’ll clean up the initial implementation, extract notification senders behind an interface, introduce a factory abstraction, and wire everything together with dependency injection.

You’ll learn how to:

Recognize when object creation is making your service too complex
Remove duplicated logic and replace magic strings with enums
Encapsulate notification implementations behind INotificationSender
Implement a factory using a dictionary-based approach
Use .NET keyed services for cleaner dependency resolution
Extend the system with a new notification channel
Understand the difference between the Factory and Strategy patterns

By the end, our original service becomes much smaller, easier to test, and easier to extend without adding more conditional logic.

Check out my courses:
https://www.milanjovanovic.tech/courses

Read my Blog here:
https://www.milanjovanovic.tech/blog

Join my weekly .NET newsletter:
https://www.milanjovanovic.tech

Chapters