Search code examples
c#asp.net-coredependency-injectionautofac

Get instances of generic class for specific type


I have generic class Module with EntityBase template parameter.

public class Module<TEntity> : where TEntity : EntityBase 
{
}

public class City : EntityBase {}
public class Country : EntityBase {}
...

Can I use autofac to get instances of Module class with specific class as template param?

E.g. Module<City>, Module<Country>. I don't want to inherit Module<T> for every class in my model.


Solution

  • You can register the module with your container like so:

    builder
        .RegisterGeneric(typeof(Module<>>)
        .AsSelf();
    

    And then you can inject them into your service's constructor:

    public SomeService(Module<City> cityModule, Module<Country> countryModule)
    

    You can see more examples in the documentation here.