I have a problem in regard to understand asp net core service provider. I register a service type with a non-generic concrete and an open generic registration,
AddTransient(typeof(IBase<Config>), typeof(Base));
AddTransient(typeof(IBase<>), typeof(BaseGeneric<>));
when I try to resolve all services, the behavior is not what I expected.
I create an empty web app with:
dotnet new web
and change the program.cs like following
ServiceCollection sc = new ServiceCollection();
sc.AddTransient(typeof(IBase<Config>), typeof(Base));
sc.AddTransient(typeof(IBase<>), typeof(BaseGeneric<>));
var serviceProvider = sc.BuildServiceProvider();
var services2 = serviceProvider.GetServices(typeof(IBase<Config>));
foreach (var s in services2){
Console.WriteLine(s.GetType());
}
Console.WriteLine();
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient(typeof(IBase<Config>), typeof(Base));
builder.Services.AddTransient(typeof(IBase<>), typeof(BaseGeneric<>));
var app = builder.Build();
var services = app.Services.GetServices(typeof(IBase<Config>));
foreach (var s in services){
Console.WriteLine(s.GetType());
}
app.MapGet("/", () => "Hello World!");
app.Run();
public class Config { }
public interface IBase<T> { }
public class BaseGeneric<T> : IBase<T> { }
public class Base : IBase<Config> { }
the output of two foreach is
Base
BaseGeneric`1[Config]
Base
Base
I expect two foreach print same result.but as you can see they return different results. Is this a valid assumption that they should work like each other? if yes so what is the problem here? and another thing that I found is if you change the order of builder.Services registration the result is OK.