For a SingletonObject, Why can I add dependency on a Transient object but not on a Scoped object in C#?

64 Views Asked by At

I am writing an Azure function and I have 2 classes Dependent and Parent. The below code shows the dependency chain. Dependent uses instance of Parent class.

public Dependent(Parent parent)
{
    Parent = parent;
}

If I set the lifetime of Parent to be transient then the code works.

public override void Configure(IFunctionsHostBuilder builder)
{
    builder.Services.AddTransient<Parent>();
    builder.Services.AddSingleton<Dependent>();
}

But if I Set the lifetime of Parent to be Scoped then I get the following error.

[2023-09-28T11:14:54.195Z] Executed 'Function1' (Failed, Id=19772818-9385-4382-8c53-116589abb2fa, Duration=1ms) [2023-09-28T11:14:54.199Z] Microsoft.Azure.WebJobs.Script.WebHost: Dependency FunctionApp1.Parent {ReturnDefault} as parameter "parent" reuse CurrentScopeReuse {Lifespan=100} lifespan shorter than its parent's: singleton FunctionApp1.Dependent {ReturnDefault} #150 [2023-09-28T11:14:54.204Z] from scoped container with {no name}

Transient dependency is shorter than scoped but it works for Transient but not for Scoped. Why is it so ?

0

There are 0 best solutions below