I'm trying to figure out the syntax to register a particular implementation of an interface and I just can't suss it out (using Simple Injector). My interface signature looks like this:
public interface IAdditionalDataService<TResult, TModel>
I would like to register an implementation for whenever the first type parameter is an IEnumerable of type TModel, for example:
public class CompositeAdditionalDataService<TModel>
: IAdditionalDataService<IEnumerable<TModel>, TModel>
How would I do this?
I've tried this:
container.RegisterOpenGeneric(typeof(IAdditionalDataService<,>),
typeof(CompositeAdditionalDataService<>));
And I get an error when I verify the container saying that there is no registration for IAdditionalDataService<List<User>, User>
, so my registration has not worked.
I've also tried this:
container.RegisterOpenGeneric(typeof(IAdditionalDataService<IEnumerable<>,>),
typeof(CompositeAdditionalDataService<>));
But this doesn't even compile, obviously, because it's not valid syntax.
So my question is
How can I register my implementation so it is used whenever a IAdditionalDataService, TModel> is requested, where TModel is a type parameter, so it could be almost anything?
You should change your generic implementation to the following:
public class CompositeAdditionalDataService<TCollectionResult, TModel>
: IAdditionalDataService<TCollectionResult, TModel>
where TCollectionResult : IEnumerable<TModel>
and register it as follows:
// Simple Injector v3.x
container.Register(
typeof(IAdditionalDataService<,>),
typeof(CompositeAdditionalDataService<,>));
// Simple Injector v2.x
container.RegisterOpenGeneric(
typeof(IAdditionalDataService<,>),
typeof(CompositeAdditionalDataService<,>));