Microsoft.Extensions.DependencyInjection中(下面简称DI),在调用ServiceProvider和IServiceScope对象的Dispose()方法时,也会自动调用ServiceProvider和IServiceScope对象通过DI创建的对象的Dispose()方法(前提是,通过DI创建的对象实现了IDisposable接口)。
我们新建一个.NET Core控制台项目,然后假设我们有接口IPeople和类People,类People实现了接口IPeople和IDisposable,接口IPeople和类People之间的依赖注入关系是Transient。
如果我们用ServiceProvider对象通过DI创建一个People对象,那么当调用ServiceProvider对象的Dispose()方法时,People对象的Dispose()方法也会被自动调用:
using Microsoft.Extensions.DependencyInjection; using System; namespace NetCoreDITransientInScope { interface IPeople { void DoSomething(); } class People : IPeople, IDisposable { public void Dispose() { Console.WriteLine("Disposing People"); } public void DoSomething() { Console.WriteLine("DoSomething is running"); } } class Program { static void Main(string[] args) { IServiceCollection services = new ServiceCollection(); services.AddTransient<IPeople, People>();//注册接口IPeople和类People的关系为Transient ServiceProvider rootServiceProvider = null; try { rootServiceProvider = services.BuildServiceProvider(); IPeople people = rootServiceProvider.GetService<IPeople>(); people.DoSomething(); } finally { if (rootServiceProvider != null) { rootServiceProvider.Dispose();//调用ServiceProvider.Dispose()方法,也会调用ServiceProvider通过DI创建的people对象的Dispose()方法 } } Console.WriteLine("Press any key to end..."); Console.ReadKey(); } } }
如果我们用IServiceScope对象的ServiceProvider通过DI创建一个People对象,那么当调用IServiceScope对象的Dispose()方法时,People对象的Dispose()方法也会被自动调用:
using Microsoft.Extensions.DependencyInjection; using System; namespace NetCoreDITransientInScope { interface IPeople { void DoSomething(); } class People : IPeople, IDisposable { public void Dispose() { Console.WriteLine("Disposing People"); } public void DoSomething() { Console.WriteLine("DoSomething is running"); } } class Program { static void Main(string[] args) { IServiceCollection services = new ServiceCollection(); services.AddTransient<IPeople, People>();//注册接口IPeople和类People的关系为Transient ServiceProvider rootServiceProvider = null; IServiceScope serviceScope = null; try { rootServiceProvider = services.BuildServiceProvider(); try { serviceScope = rootServiceProvider.CreateScope(); IPeople people = serviceScope.ServiceProvider.GetService<IPeople>(); people.DoSomething(); } finally { if (serviceScope != null) { serviceScope.Dispose();//调用IServiceScope.Dispose()方法,也会调用在serviceScope中DI创建的people对象的Dispose()方法 } } } finally { if (rootServiceProvider != null) { rootServiceProvider.Dispose(); } } Console.WriteLine("Press any key to end..."); Console.ReadKey(); } } }
关于Microsoft.Extensions.DependencyInjection会自动释放DI创建的对象,可以查看下面这篇微软的官方文档:
关于Microsoft.Extensions.DependencyInjection的详细介绍,可以查看下面微软的官方文档:
标签:People,ServiceProvider,DI,Dispose,rootServiceProvider,Extensions,IPeople,Depende From: https://www.cnblogs.com/OpenCoder/p/18227541