Location>code7788 >text

Implementation and application of generic + dependency injection in .NET

Popularity:989 ℃/2025-02-14 10:09:49

Injecting generic dependencies is a common scenario in .NET.

Using generics in dependency injection (DI) can make applications more modular, easy to test and scale.

Register a generic service in Core

Suppose we have a generic interface that needs to be injectedIRepository<T>and implementation classesRepository<T>

public interface IRepository<T>
 {
     T GetById(int id);
 }

 public class Repository<T> : IRepository<T>
 {
     public T GetById(int id)
     {
         // Simulate to get data from the database
         return default(T);
     }
 }

Next, we need toRepository<T>Register into the DI container.

In Core, you can useAddTransientAddScopedorAddSingletonMethod to register for a service.

To support generics, we can use the following methods:

public void ConfigureServices(IServiceCollection services)
 {
     // Register a generic service
     (typeof(IRepository<>), typeof(Repository<>));
 }

This code does the following:

  • IRepository<>is a generic interface that represents any type ofIRepository<T>
  • Repository<>is a generic class that implementsIRepository<T>

Inject generic services

When you want to use it in a controller or other classIRepository<T>When you can get it by constructor injection.

public class MyController : Controller
{
    private readonly IRepository<MyEntity> _repository;

    public MyController(IRepository<MyEntity> repository)
    {
        _repository = repository;
    }

    public IActionResult GetEntity(int id)
    {
        var entity = _repository.GetById(id);
        return Ok(entity);
    }
}

In this example,MyControllerThe type will be automatically retrievedIRepository<MyEntity>Examples of .

Core's dependency injection container will automatically parse and provideRepository<MyEntity>

Generic factory methods

If you need to create generic services dynamically based on different types, you can use the generic factory method. For example, you can choose different service implementations according to the conditions at runtime.

public interface IFactoryService
{
    IRepository<T> CreateRepository<T>();
}

public class FactoryService : IFactoryService
{
    private readonly IServiceProvider _serviceProvider;

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

    public IRepository<T> CreateRepository<T>()
    {
        return _serviceProvider.GetRequiredService<IRepository<T>>();
    }
}

existFactoryServiceIn the class, we useIServiceProviderTo manually parse generic types. Then, we willFactoryServiceRegister into the DI container:

public void ConfigureServices(IServiceCollection services)
{
    (typeof(IRepository<>), typeof(Repository<>));
    <IFactoryService, FactoryService>();
}

That way, you can passFactoryServiceDynamically create any type ofIRepository<T>

summary

Injecting generic services is very simple in .NET. By using Core's dependency injection framework, you can:

  • Register generic interfaces and implementation classes.
  • Inject generic services through constructors in a controller or service.
  • Use factory methods to create generic services dynamically.

These features make your code more flexible and scalable. Hopefully this article will help you better understand how to use generics for dependency injection in Core!