The Battle of the Item Services in .NET Core

Who Gets Injected First, Let’s See…

DotNet Full Stack Dev
3 min readOct 8, 2024

Imagine you’re the director of a prestigious, high-tech orchestra, and your musicians (services) are ready to perform. You’ve got ItemService1 and ItemService2, both equally talented, but when it’s showtime, only one can take the stage first. The spotlight is ready. The question is: Which service does .NET Core choose to inject when you’ve registered more than one?

Let’s dive into this intriguing showdown and uncover the secrets of Dependency Injection in .NET Core — because this is more than just code, it’s a symphony of logic!

Embark on a journey of continuous learning and exploration with DotNet-FullStack-Dev. Uncover more by visiting our https://dotnet-fullstack-dev.blogspot.com reach out for further information.

🎼 Setting the Stage: The Multiple Service Dilemma

Here’s how the plot thickens. In your Startup.cs, you register both services like this:

services.AddScoped<IItemService, ItemService1>();
services.AddScoped<IItemService, ItemService2>();

Now you’re wondering: When I ask .NET Core for IItemService, which one is handed over first?

This isn’t just a simple coin toss. There’s a method behind this orchestration. So, let’s pull back the curtain and reveal the magic!

🎩 Who Takes the Lead? It’s All About the Last One Standing!

Here’s the trick: When multiple implementations of the same interface are registered in the DI container, the last registered service wins by default.

Let’s break this down:

  • First, you registered ItemService1.
  • Then, you registered ItemService2.

And here’s the kicker: since ItemService2 was registered last, it’s the one that steps up to perform when you ask for IItemService.

In this epic battle of services, ItemService2 takes the lead because .NET Core’s DI container resolves services in the order they were registered — last one in, first one out (yes, it’s a LIFO situation).

🤔 But What If You Need Both Services to Shine?

Now, what if you’re not looking for a solo performance, but a duet? What if you want to inject both ItemService1 and ItemService2 in different parts of your app? Fear not! Here are a couple of ways you can orchestrate this.

🎶 Option 1: Inject Them All With IEnumerable

Why limit yourself to one service when you can have both? You can inject all implementations of IItemService by leveraging IEnumerable<IItemService> like this:

public class ItemController
{
private readonly IEnumerable<IItemService> _itemServices;

public ItemController(IEnumerable<IItemService> itemServices)
{
_itemServices = itemServices;
}

public void PlayBothServices()
{
foreach (var service in _itemServices)
{
service.ProcessItems();
}
}
}

Now, both ItemService1 and ItemService2 will be injected, allowing you to play them together in harmony. 🎻

🧙 Option 2: Call the Magic Factory!

If you need more control over which service to use based on specific conditions, you can wield the power of the Factory Pattern to dynamically choose your service. It’s like being the conductor of your service orchestra, calling on whichever one fits the moment.

public class ItemServiceFactory
{
private readonly IServiceProvider _serviceProvider;

public ItemServiceFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}

public IItemService GetService(string type)
{
return type switch
{
"Online" => _serviceProvider.GetService<ItemService1>(),
"Offline" => _serviceProvider.GetService<ItemService2>(),
_ => throw new ArgumentException("Invalid service type")
};
}
}

Now you’ve got the power to switch between services on the fly, directing them as you see fit.

⚖️ Wrapping Up: Orchestrating Your Service Symphony

When you register multiple implementations of an interface, remember that the last one registered will be the first one injected by default. But, with the power of .NET Core’s DI container, you can choose to inject them all or use design patterns like the Factory Pattern to inject the right service at the right time.

Whether you’re leading with ItemService1, ItemService2, or both, the decision lies in your hands as the conductor of your service symphony.

🎼 So, the next time you face the challenge of multiple service registrations, remember: it’s all about the order in which you set the stage!

What about you? How do you orchestrate your services in .NET Core? Let me know how you’re solving the “who gets called first” dilemma in your projects!

--

--

DotNet Full Stack Dev
DotNet Full Stack Dev

Written by DotNet Full Stack Dev

Join me to master .NET Full Stack Development & boost your skills by 1% daily with insights, examples, and techniques! https://dotnet-fullstack-dev.blogspot.com

Responses (1)