What is IServiceCollection in C#: Simple Explanation and Example
IServiceCollection is an interface in C# used to register services for dependency injection. It acts like a list where you add all the services your app needs, so they can be created and managed automatically.How It Works
Think of IServiceCollection as a shopping list for your app's services. Instead of creating objects manually everywhere, you add them to this list with instructions on how to make them. Later, the app uses this list to build and provide the right service whenever needed.
This helps keep your code clean and organized, like having a personal assistant who knows exactly where to find what you need. It supports different lifetimes for services, meaning some can be created once and reused, while others are made fresh each time.
Example
This example shows how to register a simple service using IServiceCollection and then retrieve it to use.
using System; using Microsoft.Extensions.DependencyInjection; public interface IMessageService { void SendMessage(string message); } public class ConsoleMessageService : IMessageService { public void SendMessage(string message) { Console.WriteLine($"Message: {message}"); } } class Program { static void Main() { // Create a new service collection var services = new ServiceCollection(); // Register the IMessageService with its implementation services.AddTransient<IMessageService, ConsoleMessageService>(); // Build the service provider var serviceProvider = services.BuildServiceProvider(); // Get the service and use it var messageService = serviceProvider.GetService<IMessageService>(); messageService.SendMessage("Hello from IServiceCollection!"); } }
When to Use
Use IServiceCollection when you want to manage dependencies in your C# app cleanly and efficiently. It is especially helpful in larger projects or web apps where many parts need to work together without tightly coupling code.
Common scenarios include ASP.NET Core applications, console apps with complex logic, or any project where you want to easily swap implementations or manage object lifetimes automatically.
Key Points
- IServiceCollection is a container to register services for dependency injection.
- It helps create and manage service lifetimes like transient, scoped, and singleton.
- Used mainly in ASP.NET Core but useful in any C# app needing dependency management.
- Improves code modularity, testability, and maintainability.
Key Takeaways
IServiceCollection registers services for automatic creation and management.