Home > Blockchain >  Get instances of generic class for specific type
Get instances of generic class for specific type

Time:05-17

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.

CodePudding user response:

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.

  • Related