Veoxer
Veoxer

Reputation: 442

Dynamic dependency injection of a generic class

I'm pretty new to the .Net world and I faced a problem that I couldn't find a solution to and I would like you to help me with it please.

I have a generic class that implements a generic interface and when I was implementing the dependency injection I didn't know how I can make it dynamic.

For example:

services.AddSingleton<IGenericRepository<Game>, GenericRepository<Game>>();

I have multiple classes that i want to pass to the generic class/interface (Game is one of them) and I know that I have to repeat this line for every single one of them but i was wondering of there is any way to make this dynamic.

Thank you.

Upvotes: 0

Views: 2166

Answers (2)

xander
xander

Reputation: 1709

What you're looking for is called an "open generic" registration. You didn't say exactly what DI framework you're using, but for most DI frameworks, the syntax is something like:

services.AddSingleton(typeof(IGenericRepository<>), typeof(GenericRepository<>));

My guess is that you're using Microsoft DI framework. If so, the relevant documentation is here. Search for the word "generic".

Upvotes: 3

Matt U
Matt U

Reputation: 5118

You could probably use reflection to load all your model types, if they're all in the same namespace. Something like:

// You can use Assembly.GetExecutingAssembly() if the models are in the same assembly this code runs from
var assembly = typeof(SomeTypeInAssembly).Assembly;

var modelTypes = assembly.GetTypes()
    .Where(t => t.IsClass && t.Namespace == "Namespace.For.Your.Models");

foreach (var modelType in modelTypes)
{
    services.AddScoped<IGenericRepository<modelType>, GenericRepository<modelType>>();
}

Where SomeTypeInAssembly is a type in the same assembly where your models live, and "Namespace.For.Your.Models" is the full namespace your models are in.

Upvotes: 0

Related Questions