I have 3 interfaces ( for singleton/scoped/transient) :
public interface ISingleton
{
}
class Singlet : ISingleton
{
}
public interface IScoped
{
}
class Scoped : IScoped
{
}
public interface Itransient
{
}
class Transient : Itransient
{
}
I register them as :
services.AddScoped<IScoped, Scoped>();
services.AddTransient<Itransient, Transient>();
services.AddSingleton<ISingleton, Singlet>();
If I try to inject scoped service to singleton , I should (and do) get an exception (I know the reason for this):
public interface ISingleton
{
}
class Singlet : ISingleton
{
public Singlet( IScoped sc)
{
}
}
Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: WebApplication2.ISingleton Lifetime: Singleton ImplementationType: WebApplication2.Singlet': Cannot consume scoped service 'WebApplication2.IScoped' from singleton 'WebApplication2.ISingleton'.)
But if I try to inject transient , I do not get an exception :
public interface ISingleton
{
}
class Singlet : ISingleton
{
public Singlet( Itransient tr)
{
}
}
Question:
Why does .net core forbids injecting a shorter lifetime (scoped) services raising an exception, while allowing transient to be injected to a singleton?