If you will call transient service within singleton service, transient service will be treated as singleton service, i.e. the instance of transient service will be available till the lifetime of singleton service/application.
public interface ISingleton
{
void SingltonMethod();
}
public class Singleton : ISingleton
{
public Singleton(ITransient trnasient)
{
Console.WriteLine("Singleton ctor called");
Transient = trnasient;
}
public ITransient Transient { get; }
public void SingltonMethod()
{
Console.WriteLine("Singleton Method");
Console.WriteLine(" Transient instance Id :" +Transient.GetHashCode());
}
}
public interface ITransient
{
void TransientMethod();
}
public class Transient : ITransient
{
public Transient()
{
Console.WriteLine("Transient ctor called");
}
public void TransientMethod()
{
Console.WriteLine("Transient Method");
}
}
public interface ITransientA
{
void TransientMethod();
}
public class TransientA : ITransientA
{
private readonly ITransient trns;
public TransientA()//(ITransient trns)
{
Console.WriteLine("TransientA ctor called");
//this.trns = trns;
}
public void TransientMethod()
{
Console.WriteLine("Transient A Method");
//trns.TransientMethod();
}
}
Service Registration:
builder.Services.AddSingleton<ISingleton, Singleton>();
builder.Services.AddTransient<ITransient, Transient>();
builder.Services.AddTransient<ITransientA, TransientA>();
Service injection:
app.MapGet("/", (ISingleton service,ITransient transient , ITransientA transientA) => {
service.SingltonMethod();
transientA.TransientMethod();
Console.WriteLine("transientA hashcode :"+ transientA.GetHashCode());
/transient.TransientMethod();
Console.WriteLine("transient hashcode :" + transient.GetHashCode());
});
Output:
Custom middleware before
Transient ctor called
Singleton ctor called
Transient ctor called
TransientA ctor called
Singleton Method
Transient instance Id :39449526
Transient A Method
transientA hashcode :50346327
Transient Method
transient hashcode :50874780
Custom middleware After!
Custom middleware before
Transient ctor called
TransientA ctor called
Singleton Method
Transient instance Id :39449526
Transient A Method
transientA hashcode :11404313
Transient Method
transient hashcode :64923656
Custom middleware After!
clearly, we can see that instance of transient dependency within singleton is same all the time, while in other injections we are getting new instance.
No comments:
Post a Comment