简体   繁体   中英

How to resolve dependency injection with class constructor that takes two implementations of the same interface

I only know basics of IoC. For the sake of simplicity (uhh), I want to stay with Microsoft.Extensions.DependencyInjection .

The IProcessor interface (and IData one which I don't detail and is implemented by Excel and SQLServer classes):

public interface IProcessor
{
    List<FielModel> ReadFieldsFromExcel();
    List<FieldModel> ReadFieldsFromSQLServer();
}

The Processor implementation:

public class Processor : IProcessor
{
    private readonly IData _excel;
    private readonly IData _sqlServer;
    
    public Processor(IData excel, IData sqlServer)
    {
        _excel = excel;
        _sqlServer = sqlServer;
    }
    
    public List<FielModel> ReadFieldsFromExcel();
    {
        // ..
    }
    
    public List<FieldModel> ReadFieldsFromSQLServer();
    {
        // ..
    }
}

The main Program with the DI.

class Program
{
    private static ServiceProvider _serviceProvider;
    
    static void Main(string[] args)
    {
        RegisterServices();
        
        var processor = _serviceProvider.GetService<IProcessor>();
        
        // ..
    }
    
    private static void RegisterServices()
    {
        // Setups dependency injection
        var service = new ServiceCollection()
            .AddSingleton<IProcessor, Processor>()
            .AddSingleton<IData, Excel>()
            .AddSingleton<IData, SQLServer>()
            .AddSingleton<Program>();
            
        _serviceProvider = service.BuildServiceProvider();
    }
}

The problem is that both excel and slqServer are instantiated to SQLServer (ie the last IData registered singleton). How can I resolve this instatiation via dependency injection?

I already found a way to instantiate specific class the following way, but I don't think it is directly (and implicitly) applicable to a class constructor...

var excel = _serviceProvider.GetServices<IData>()
                            .First(o => o.GetType() == typeof(Excel));

Thanks for any insights.

You could register a delegate:

var service = new ServiceCollection()
    .AddSingleton<Excel>()
    .AddSingleton<SQLServer>()
    .AddSingleton<IProcessor>(provider =>
        new Processor(
            provider.GetRequiredService<Excel>(),
            provider.GetRequiredService<SQLServer>())
    .AddSingleton<Program>();
        

The simplest way is to declare a marker interface for each specific implementation:

public interface IExcelData : IData { /* nothing */ }

public class Excel : IExcelData { ... }

public interface ISqlServerData : IData { /* nothing */ }

public class SqlServer : ISqlServerData { ... }
public class Processor : IProcessor
{
    private readonly IData _excel;
    private readonly IData _sqlServer;
    
    public Processor(IExcelData excel, ISqlServerData sqlServer)
    {
        _excel = excel;
        _sqlServer = sqlServer;
    }

    ...
}
services
    .AddSingleton<IExcelData, Excel>()
    .AddSingleton<ISqlServerData, SQLServer>()
    ...

BTW, instead of manually creating the dependency containers, you should look into using the generic host: https://docs.microsoft.com/en-us/dotnet/core/extensions/generic-host

You could also inject an IEnumerable<YourDependency> if the two concrete types are registered against the same interface.

public class Processor : IProcessor
{
    private readonly IEnumerable<IData> _dataDependencies;
    
    public Processor(IEnumerable<IData> dataDependencies)
    {
        _dataDependencies= dataDependencies;
    }
}

You could then resolve the relevant type by having some sort of Enum on the implementing class that you can use to select the appropriate service. I will use a simple string example to illustrate. (you probably shouldn't do it this way)

public class Processor : IProcessor
{
    private readonly IEnumerable<IData> _dataDependencies;
    
    public Processor(IEnumerable<IData> dataDependencies)
    {
        var selectedDependency = dataDependencies.FirstOrDefault(dep => dep.Type == "Excel");
    }
}

Please try this.

var excel = _serviceProvider.GetServices<Excel.IData>();
                        

After reading comment .

You can change constructor as following.

 public Processor(Excel.IData excel, SQLServer.IData sqlServer)
    {
        _excel = excel;
        _sqlServer = sqlServer;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM