How to register generic types with multiple type arguments in dotnet core for dependency injection?

Viewed 65

Using Dotnet Core 3.1, I use the built in DI solution.

I'm implementing a datapump, that uses a data source and a data target, all of them generics:

public interface IDataSource<TData> where TData : class {}

public interface IDataTarget<TData> where TData : class {}

public interface IDataPump<TSourceData, TTargetData>
     where TSourceData : class
     where TTargetData : class {}

public class DataPump<TSourceData, TTargetData> : IDataPump<TSourceData, TTargetData>
     where TSourceData : class
     where TTargetData : class {}

I found examples on how to DI register the types with a single type argument, but how to register IDataPump / DataPump with two type arguments?

1 Answers

Once I know the answer it's really simple, just had to add a comma to signify the number of type arguments:

serviceCollection
    .AddSingleton(typeof(IDataSource<>), typeof(DataSource<>))
    .AddSingleton(typeof(IDataTarget<>), typeof(DataTarget<>))
    .AddSingleton(typeof(IDataPump<,>), typeof(DataPump<,>))
Related