❗You're Using Dependency Injection Wrong - Use THIS Instead


Hey Reader,

Ever tried to choose the perfect weapon for each creature in a dark, spooky forest? Silver bullets for werewolves, garlic for vampires, chainsaws for zombies... but what if you had to pick your weapon before entering the forest? Just like that forest adventure, dependency injection in C# can leave you stuck with the wrong tool when you need it most - unless you know about the Factory Pattern!

Today, I’m breaking down how the Factory Pattern solves real-world dependency injection issues and when to use it instead of conventional DI. If you’re interested in dynamically switching dependencies at runtime (instead of being locked in beforehand), this is for you!

Watch on YouTube 📺

Check out the full tutorial to see how the Factory Pattern saves the day 👇

video preview

The Problem: Static Dependencies in DI

In typical dependency injection, you declare services upfront, which locks in certain dependencies at compile time. Let’s say we’re working with different services to handle weapons:


public interface IWeaponService
{
    string GetWeapon();
}
public class VampireWeaponService : IWeaponService
{
    public string GetWeapon() => "Garlic";
}
public class WerewolfWeaponService : IWeaponService
{
    public string GetWeapon() => "Silver Bullet";
}
public class ZombieWeaponService : IWeaponService
{
    public string GetWeapon() => "Chainsaw";
}

Registered in the Program.cs:

builder.Services.AddScoped

But here’s the catch: this setup only lets you pick one weapon before runtime. That’s fine if you’re only fighting vampires, but if you encounter a zombie with garlic in hand… well, you’re out of luck!

The Factory Pattern Solution

Enter the Factory Pattern! With this approach, we can dynamically choose the right weapon at runtime based on the creature we’re facing. Here’s how it’s done:

Step 1: Define a Factory Interface


public interface IWeaponFactory
{
    IWeaponService Create(string creatureType);
}

Step 2: Implement the Factory


public class WeaponFactory : IWeaponFactory
{
    private readonly IServiceProvider _serviceProvider;
    public WeaponFactory(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }
    public IWeaponService Create(string creatureType)
    {
        return creatureType switch
        {
            "Vampire" => _serviceProvider.GetRequiredService(),
            "Werewolf" => _serviceProvider.GetRequiredService(),
            "Zombie" => _serviceProvider.GetRequiredService(),
            _ => throw new ArgumentException("Unknown creature type!")
        };
    }
}

Step 3: Register Services and Factory in Program.cs

builder.Services.AddScoped

builder.Services.AddScoped

builder.Services.AddScoped

builder.Services.AddScoped

Step 4: Implement in Controller

Here’s how it looks in a simple BattleController with a POST method to select the right weapon:


[ApiController]
[Route("api/[controller]")]
public class BattleController : ControllerBase
{
    private readonly IWeaponFactory _weaponFactory;
    public BattleController(IWeaponFactory weaponFactory)
    {
        _weaponFactory = weaponFactory;
    }
    [HttpPost("fight")]
    public ActionResult Fight(string creatureType)
    {
        var weaponService = _weaponFactory.Create(creatureType);
        var weapon = weaponService.GetWeapon();
        return Ok($"Fighting a {creatureType} with {weapon}!");
    }
}

Now, instead of committing to one weapon upfront, you’re armed for any creature you face! ⚔️


Want More?

Ready to master .NET and Blazor? Join the .NET Web Academy and enjoy 10% off with the code HALLOWEEN24 until Friday. Learn from real-world examples and dive deep into patterns that’ll make you a better developer. Just check out the link in the video description and hear what real students have to say!

Happy coding and good luck defeating those creatures! 🧛‍♂️🧟‍♂️

Take care,
Patrick

Patrick God

Become a .NET & Blazor expert with weekly tutorials featuring best practices and the latest improvements, right in your inbox.

Read more from Patrick God

Hey Reader, Last week, I tested GPT-5 Agent Mode on .NET and Blazor apps, and the results were surprising. This week, I went a step further. I used GitHub Copilot inside Visual Studio and asked it to create real .NET and Blazor projects for me. Here’s what happened: Copilot generated a working calculator app in C#. It built a Web API that responded with “Hello GPT-5 Agents.” It even created a Blazor app with extra features like a reset button, a plus five counter, and a weather API. Were...

video preview

Hey Reader, I just published a new video where I put GPT-5’s Agent Mode to the test. 🚀 Instead of asking it for something simple, I went all in: A .NET 9 console app calculator A Web API with endpoints and docs A Blazor Server app with extra counter buttons And even a Blazor app that calls a public weather API 🎥 Watch it now: In the video, I didn’t just type “make me an app” and hope for the best. I gave GPT-5 very specific prompts, like: “Please create a .NET 9 console application that works...

Hey Reader, I’m back! 🎉 I’ve been on parental leave for the past 2 months, enjoying time with the family. Now I’m diving back into videos and here’s the first one! 🎥 Watch it now: Here’s the TL;DR if you can’t click right now: AI can already write code, fix bugs, and explain complex concepts. So… are we doomed? No. AI isn’t replacing developers anytime soon. But: Developers who use AI will replace those who don’t. The best devs are using GPT to: Skip repetitive work Prototype faster Learn...