Replace service registration in ASP.NET Core built-in DI container?

前端 未结 3 1584
悲哀的现实
悲哀的现实 2020-12-05 17:15

Let us consider a service registration in Startup.ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
    services.A         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 17:53

    Just to add on @ilya-chumakov 's great answer, here is the same method but with support for implementation factories

    public static IServiceCollection Replace(
        this IServiceCollection services,
        Func implementationFactory,
        ServiceLifetime lifetime)
        where TService : class
    {
        var descriptorToRemove = services.FirstOrDefault(d => d.ServiceType == typeof(TService));
    
        services.Remove(descriptorToRemove);
    
        var descriptorToAdd = new ServiceDescriptor(typeof(TService), implementationFactory, lifetime);
    
        services.Add(descriptorToAdd);
    
        return services;
    }
    

    in case we want to use it with a factory that instantiates the service like the following sample:

    var serviceProvider = 
      new ServiceCollection()
        .Replace(sp => new MyService(), ServiceLifetime.Singleto)
        .BuildServiceProvider();
    

提交回复
热议问题