Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection ASP.NET Core: Register multiple implementations

I have the following classes structure:

interface IContractService{}

class Service1 : IContractService{}

class Service2 : IContractService{}

class ContractServiceFactory
{
    private readonly IServiceProvider _serviceProvider;
     ContractServiceFactory(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;            
    }
     IContractService GetContractService(string standard)
    {
        // Is it possible to retrieve service by string const???
        return _serviceProvider.GetRequiredService<IContractService>(standard);
    }
}

In the services collection I would like to add my classes in the following way:

builder.Services.AddScoped<IContractService, ContractService1>("standard1");
builder.Services.AddScoped<IContractService, ContractService2>("standard2");

Is it possible in .net core 2.1?

like image 890
Volter1989 Avatar asked Oct 22 '25 01:10

Volter1989


1 Answers

You could do it using factory:

So first you need to define your 2 services:

services.AddScoped<Service1>();
services.AddScoped<Service2>();

services.AddScoped<Func<int, IContractService>>(serviceProvider=> key=>
{
    switch(key)
    {
        case 1:
           return serviceProvider.GetService<Service1>();
        case 2:
           return serviceProvider.GetService<Service2>();
        default:
            throw new Exception("Not valid key");
    }
});

Here docs.microsoft for GetService, you could use some kind of enumeration instead of plain int

After that in your controller:

public class HomeController:Controller
{

    private readonly Service1 _service1;   

    public HomeController(Func<int, IContractService> serviceProvider)
    {
        _service1 = serviceProvider(1);            
    }

}
like image 122
mybirthname Avatar answered Oct 24 '25 14:10

mybirthname



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!