使用带有 Microsoft.Extensions.DependencyInjection 库的服务进行依赖注入

Dependency injection using Services with Microsoft.Extensions.DependencyInjection library

为什么在第二次创建作用域后没有调用 ScopedOperation 构造函数?

来源:https://dotnetfiddle.net/wtyP9n

using System;
using Microsoft.Extensions.DependencyInjection;
                    
public class Program
{
    public static void Main()
    {

添加服务:

        var serviceProvider = new ServiceCollection()
            .AddTransient<TransientOperation>() //Create a Simple Transient Service that writes a text on creation
            .AddScoped<ScopedOperation>()       //Create a Simple Scoped Service  that writes a text on creation
            .AddSingleton<SingletonOperation>() //Create a Simple Singleton Service  that writes a text on creation

构建服务并发出第一个请求:

         serviceProvider.BuildServiceProvider();
        
         Console.WriteLine("Initiating Service Operations");
        
         Console.WriteLine("\n-------- First Request --------");    
        
        //With the scope the aim is to see if after the using(), which service will be destroyed
         using (var scope = serviceProvider.CreateScope())
         {
            var singletonService = serviceProvider.GetService<SingletonOperation>();  
            var scopedService = serviceProvider.GetService<ScopedOperation>();  
            var transientService = serviceProvider.GetService<TransientOperation>();  
         } //Why the disposed methods of Scoped and Transient Services are not being called ?

进入第二个请求:

         Console.WriteLine("\n-------- Second Request --------");        
         using (var scope = serviceProvider.CreateScope()) //adding the same singleton, scope and transient services agains
         {
            var singletonService = serviceProvider.GetService<SingletonOperation>();  
            var scopedService = serviceProvider.GetService<ScopedOperation>();
            var transientService = serviceProvider.GetService<TransientOperation>();
         } //Why the disposed methods of Scoped and Transient Services are not being called ?
                  
         Console.WriteLine();
         Console.WriteLine(new String('-',30));
         Console.WriteLine("Operations Concluded!");
         Console.ReadLine();
    }
}

//DEFINING THE SERVICES

服务:

public class SingletonOperation:IDisposable 
{   private bool _disposed = false; 
    public SingletonOperation() =>  Console.WriteLine("Singleton Service created!");   
    public void Dispose() { if (_disposed) return; Console.WriteLine("SingletonService Disposed!"); _disposed = true;}
    ~SingletonOperation() => Dispose();
}
public class ScopedOperation:IDisposable
{ 
    private bool _disposed = false;
    public ScopedOperation() =>  Console.WriteLine("Scoped Service created!");  
    public void Dispose() { if (_disposed) return;  Console.WriteLine("ScopedService Disposed!");_disposed = true; }
    ~ScopedOperation()=>Dispose();
}
public class TransientOperation:IDisposable
{   private bool _disposed = false;
    public TransientOperation() =>  Console.WriteLine("Transient Service created!");   
    public void Dispose(){ if (_disposed) return; Console.WriteLine("TransientService Disposed!"); _disposed = true;    }
    ~TransientOperation() => Dispose();
}

显示完整结果:

Observe that on the Second Request, the Transient Service constructor was called, but I was expecting also the ScopedService Constructor to also be called since it is in a different scope. Why it was not called ?

//Why the disposed methods of Scoped and Transient Services are not being called ?

您的示例的提供程序未被处置,因此其创建的服务也不会被处置。您示例中的所有 GetService 调用都属于同一范围。

使用创建范围的提供程序来获得所需的行为

//...

using (IServiceScope scope = serviceProvider.CreateScope()) {
    var singletonService = scope.ServiceProvider.GetService<SingletonOperation>();  
    var scopedService = scope.ServiceProvider.GetService<ScopedOperation>();  
    var transientService = scope.ServiceProvider.GetService<TransientOperation>();  
} 

//...

对提供的 fiddle 进行上述更改产生以下输出

Initiating Service Operations

-------- First Request --------
Singleton Service created!
Scoped Service created!
Transient Service created!
TransientService Disposed!
ScopedService Disposed!
Executing DemoService Operation number: 0 
Executing DemoService Operation number: 1 
Initialized valued on service was: 10 
Adding object of type Client
I am Service A
I am Service B
I am Service B

-------- Second Request --------
Scoped Service created!
Transient Service created!
TransientService Disposed!
ScopedService Disposed!

------------------------------
Operations Concluded!