ASP.NET Core Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

ASP.NET Core - Extension class to register services for Dependency Injection

Back to: ASP.NET Core Tutorial

In .NET Core, you can create an extension class to register services for dependency injection, which allows for cleaner and more modular code. An extension class helps encapsulate the dependency injection setup for specific services, making it reusable and easy to call from the Startup class or from the Program.cs file if you're using a minimal hosting model.

Here's an example of how to create an extension class for dependency injection in .NET Core.

Step 1: Create the Service Interface and Implementation

First, define an interface and a service that you want to register.

csharp
// Services/IMyService.cs
public interface IMyService
{
void DoWork();
}
// Services/MyService.cs
public class MyService : IMyService
{
public void DoWork()
{
// Implementation of the work
Console.WriteLine("Work is done!");
}
}

Step 2: Create an Extension Class for Service Registration

Now, create a static class to hold the extension method, where you'll register your service.

csharp
// Extensions/ServiceExtensions.cs
using Microsoft.Extensions.DependencyInjection;
public static class ServiceExtensions
{
public static IServiceCollection AddMyServices(this IServiceCollection services)
{
services.AddScoped<IMyService,MyService>();
// Register other services here if needed
return services;
}

Step 3: Register the Services in Program.cs or Startup.cs

Finally, use the extension method in Program.cs or Startup.cs to register your services with the dependency injection container.

csharp
// Program.cs (for .NET 6 or later with minimal hosting)
var builder = WebApplication.CreateBuilder(args);
// Register services using the extension method
builder.Services.AddMyServices();
var app = builder.Build(); //
Use your app setup here (e.g., endpoints, middleware, etc.)
app.Run();

Or, in Startup.cs (for .NET Core 3.1 or .NET 5):

csharp
// Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Register services using the extension method
services.AddMyServices();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Middleware configuration goes here
}
}

Usage

Now, IMyService can be injected wherever it’s needed in the application, like in controllers or other classes:

csharp
public class MyController : ControllerBase
{
private readonly IMyService _myService;
public MyController(IMyService myService)
{
_myService = myService;
}
public IActionResult Get()
{
_myService.DoWork();
return Ok();
}
}

This setup keeps the registration logic organized, makes it reusable, and follows the dependency injection principles in .NET Core effectively.

Scroll to Top