Search code examples
c#.netdependency-injectionsimple-injectordi-containers

How can I map a generic abstraction to a generic implementation in Simple Injector?


I could not come of with a better title so please feel free to change it after you have read the entire question.

I have the following classes:

public class Foo<T> : IFoo<T> {}
public interface IFoo<T> { }

I would like to be able to inject IFoo<T> arguments in such a way:

public class MyService 
{
    public MyService(IFoo<SomeClass> whatever) {}
}

How can I configure the container without having to register every single registration? i.e. I want to avoid having to do this:

container.Register<IFoo<SomeClass>>(new Foo<SomeClass>());
container.Register<IFoo<SomeOtherClass>>(new Foo<SomeOtherClass>());
...

Instead I want to do something like this (pseudo code):

container.Register<IFoo<T>>(new Foo<T>());

Solution

  • Like this:

    container.Register(typeof(IFoo<>), typeof(Foo<>));
    

    Read more about it here.