- A+
所属分类:.NET技术
我们在Startup类里面可以看到那么一句话:
// This method gets called by the runtime. Use this method to add services to the container.
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddSession(); }
意思就是:要把服务注入容器里面去【core内置IOC】:当前方法被运行时环境调入,把服务添加到container容器里面去,IServiceCollection其实就是个一个容器,那我们是怎么使用,怎么解析呢???
要使用它就必须要有个接口,以及接口的实例,那我们就来写个接口实例:
/// 容器的使用: /// 1.创建一个容器的实例; /// 2.注册 /// 3.获取服务
/// <summary> /// 容器的使用实例 /// </summary> /// <param name="args"></param> static void Main(string[] args) { { Console.WriteLine("容器的使用实例"); //1.创建一个容器的实例,需要添加NuGet【Microsoft.Extensions.DependencyInjection】,同时引用命名空间 IServiceCollection container = new ServiceCollection(); //2.注册【注册有4种方式,用Add添加的方式】 //第一种瞬时生命周期,每次获取的对象都是一个新的对象 container.AddTransient<IServiceA, ServiceA>(); //第二种单例注册,单例生命周期:在容器中永远只有当前这一个 container.AddSingleton<IServiceB, ServiceB>(); //第三种作用域注册,生命周期:当前请求作用域,只有当前这个实例,除非二次请求,或者作用域不一样 container.AddScoped<IServiceC, ServiceC>(); //第四种:跟单例的生命周期一样 container.AddSingleton<IServiceD>(new ServiceD()); //3.获取服务【Alt+Shift 竖列选择】【ctrl+K+D:自动格式化】 ServiceProvider provider = container.BuildServiceProvider(); IServiceA TestA = provider.GetService<IServiceA>(); IServiceB TestB = provider.GetService<IServiceB>(); IServiceC TestC = provider.GetService<IServiceC>(); IServiceD TestD = provider.GetService<IServiceD>(); //做比较 IServiceA TestA1 = provider.GetService<IServiceA>(); IServiceB TestB1 = provider.GetService<IServiceB>(); IServiceC TestC1 = provider.GetService<IServiceC>(); IServiceD TestD1 = provider.GetService<IServiceD>(); Console.WriteLine($"瞬时生命周期比较,结果:{Object.ReferenceEquals(TestA, TestA1)}"); Console.WriteLine($"单例1的生命周期比较,结果:{ReferenceEquals(TestB, TestB1)}"); Console.WriteLine($"单例2的生命周期比较,结果:{Object.ReferenceEquals(TestD, TestD1)}"); //同一个作用域比较 Console.WriteLine($"同作用域生命周期比较,结果:{Object.ReferenceEquals(TestC, TestC1)}"); //新建一个作用域 IServiceScope scope = provider.CreateScope(); IServiceC TestC2 = scope.ServiceProvider.GetService<IServiceC>(); //不同作用域比较 Console.WriteLine($"不同作用域生命周期比较,结果:{Object.ReferenceEquals(TestC,TestC2)}"); } Console.ReadLine(); }
结果:
这边单独写了两个接口类库:Core.Interface,Core.Service
Core.Interface
public interface IServiceA { void Show(); }
public interface IServiceB { void Show(); }
public interface IServiceC { void Show(); }
public interface IServiceD { void Show(); }
Core.Service:
public class ServiceA : IServiceA { public void Show() { Console.WriteLine("ServiceA"); } }
public class ServiceB : IServiceB { public ServiceB(IServiceA iservice) { } public void Show() { Console.WriteLine("This's ServiceB"); } }
public class ServiceC : IServiceC { public ServiceC(IServiceB iservice) { } public void Show() { Console.WriteLine("This's ServiceC"); } }
public class ServiceD : IServiceD { public void Show() { Console.WriteLine("ServiceD"); } }