How does .NET dependency injection resolve between generic and specific matches?

Viewed 73

In .NET 6 you can map a generic interface to a generic implementation like this:

builder.Services.AddScoped(typeof(IService<>), typeof(Service<>));

But say you want to configure IService<Foo> to return FooService instead of the generic Service<Foo>.

If you add this line it seems to work, favoring the specific type match over the generic regardless of the order they are defined in:

builder.Services.AddScoped<IService<Foo>, FooService>();

Is this behaviour that can be depended upon, and the correct way to do this? Am I even trying to solve the right problem?

The source for the Microsoft.Extensions.DependencyInjection is here for reference.

0 Answers
Related