(82) C# .net core 依赖注入
控制反转的两种方式:1 服务定位器,2 依赖注入
服务定位器
一、服务定位器
服务:就是找框架要的一个对象
引入 Microsoft.Extensions.DependencyInjection
对象生命周期
1. AddTransient 瞬时生命周期
每次serviceProvider.GetService<Test>(); 都会创建一个对象
ServiceCollection services = new ServiceCollection(); //把对象放入 services.AddTransient<Test>(); ServiceProvider serviceProvider = services.BuildServiceProvider(); Test testService = serviceProvider.GetService<Test>(); testService.Name = "liu"; testService.Hi(); public interface ITestService { public string Name { get; set; } public void Hi(); } public class Test : ITestService { public string Name { get ; set; } public void Hi() { Console.WriteLine($"打印{Name}"); } }
2.唯一对象AddSingleton
services.AddSingleton<Test>();
ServiceCollection services = new ServiceCollection(); //把对象放入 services.AddTransient<Test>(); ServiceProvider serviceProvider = services.BuildServiceProvider(); Test testService = serviceProvider.GetService<Test>(); testService.Name = "liu"; testService.Hi(); Test testService1 = serviceProvider.GetService<Test>(); testService1.Name = "tom"; testService.Hi(); testService1.Hi();
3.范围内
ServiceCollection services = new ServiceCollection(); //把对象放入 services.AddScoped<Test>(); ServiceProvider serviceProvider = services.BuildServiceProvider(); //IServiceScope域 范围内相同 using (IServiceScope servicesScope = serviceProvider.CreateScope()) { Test testService = servicesScope.ServiceProvider.GetService<Test>(); Test testService2 = servicesScope.ServiceProvider.GetService<Test>(); } using (IServiceScope servicesScope2 = serviceProvider.CreateScope()) { Test testService = servicesScope2.ServiceProvider.GetService<Test>(); Test testService2 = servicesScope2.ServiceProvider.GetService<Test>(); }
使用接口实现
ServiceCollection services = new ServiceCollection(); //传入接口和实现类 services.AddTransient<ITestService,Test>(); ServiceProvider serviceProvider = services.BuildServiceProvider(); // ITestService testService = serviceProvider.GetService<ITestService>(); testService.Name = "liu"; testService.Hi(); //查看testService实际类型为Test Console.WriteLine(testService.GetType());
二、依赖注入
ServiceCollection services = new ServiceCollection(); services.AddTransient<Test>(); services.AddTransient<A>(); var s=services.BuildServiceProvider().GetService<Test>(); s.ok(); public interface ITest { void ok(); } public class Test : ITest { A a; public Test(A a) { this.a = a; } public void ok() { Console.WriteLine("打印ok方法"); a.AAA(); } } public interface IA { void AAA(); } public class A { public void AAA() { Console.WriteLine("打印AAA方法"); } }