Registering a generic type with a generic argument in Simple Injector

42 Views Asked by At

I want to register several interfaces having a generic argument. This is an example of the code:

container.Register(
    typeof(IDataMerger<OriginalObject, Response<MergeObjectA>>), 
    typeof(DataMerger<MergeObjectA>));

What is the best way to do this other than making a new registration for each merge object?

I have made attempts using code similar to the code below, but I am receiving an error.

container.RegisterConditional(
    typeof(IDataMerger<,>),
    typeof(DataMerger<>).MakeGenericType(typeof(ConsumerObject<,>)
        .GetGenericArguments()[1]), 
    c => c.Consumer?.ImplementationType != null
        && c.Consumer.ImplementationType.GetGenericArguments().Length == 2
        && c.Consumer.ImplementationType
              .GetGenericArguments()[0] == typeof(OriginalObject));

Any help that you can provide will be greatly appreciated.

1

There are 1 best solutions below

1
Steven On

The documentation shows examples that show how to do this.

Assuming the following definitions:

interface IDataMerger<TRequest, TResponse> { }

class DataMerger<T> : IDataMerger<OriginalObject, Response<T>> { }

you can make the following registration:

container.Register(typeof(IDataMerger<,>), typeof(DataMerger<>));