//IOC容器支持依赖注入{ServiceCollection serviceDescriptors = new ServiceCollection();serviceDescriptors.AddTransient<IMicrophone, Microphone>();serviceDescriptors.AddTransient<IPower, Power>();serviceDescriptors.AddTransient<IHeadphone, Headphone>();ServiceProvider serviceProvider =serviceDescriptors.BuildServiceProvider();IHeadphone headphone = serviceProvider.GetService<IHeadphone>();}
AddTransient:瞬时生命周期,每一次创建都是是一个全新的实例
ServiceCollection serviceDescriptors = new ServiceCollection();
serviceDescriptors.AddTransient<IMicrophone, Microphone>();
ServiceProvider serviceProvider =serviceDescriptors.BuildServiceProvider();
IMicrophone microphone1 = serviceProvider.GetService<IMicrophone>();
AddSingleton:单例生命周期:同一个类型,创建出来的是同一个实例
ServiceCollection serviceDescriptors = new ServiceCollection();
serviceDescriptors.AddSingleton<IMicrophone, Microphone>();
ServiceProvider serviceProvider = serviceDescriptors.BuildServiceProvider();
IMicrophone microphone1 = serviceProvider.GetService<IMicrophone>();
AddScoped:作用域生命周期: 同一个serviceProvider获取到的是同一个实例
ServiceCollection serviceDescriptors = new ServiceCollection();
serviceDescriptors.AddScoped<IMicrophone, Microphone>();
ServiceProvider serviceProvider1 = serviceDescriptors.BuildServiceProvider();
IMicrophone microphone1 = serviceProvider1.GetService<IMicrophone>();
ServiceCollection 抽象和具体之间多种注册方式
{ServiceCollection serviceDescriptors = new ServiceCollection();serviceDescriptors.AddTransient<IMicrophone, Microphone>();ServiceProvider serviceProvider1 = serviceDescriptors.BuildServiceProvider();IMicrophone microphone1 = serviceProvider1.GetService<IMicrophone>();
}
{ServiceCollection serviceDescriptors = new ServiceCollection();serviceDescriptors.AddTransient(typeof(IMicrophone), typeof(Microphone));ServiceProvider serviceProvider1 = serviceDescriptors.BuildServiceProvider();IMicrophone microphone1 = serviceProvider1.GetService<IMicrophone>();
}
//注册抽象和一段业务逻辑
{ServiceCollection serviceDescriptors = new ServiceCollection();serviceDescriptors.AddTransient(typeof(IPower), provider =>{//在这里可以我们自己来决定如何创建这个对象的实例;可以对创建出来的这个实例,可以做加工IMicrophone microphone = provider.GetService<IMicrophone>();return new Power(microphone);});serviceDescriptors.AddTransient(typeof(IMicrophone), typeof(Microphone));ServiceProvider serviceProvider1 = serviceDescriptors.BuildServiceProvider();IPower power = serviceProvider1.GetService<IPower>();
}
{ServiceCollection serviceDescriptors = new ServiceCollection();serviceDescriptors.AddTransient(typeof(Microphone));ServiceProvider serviceProvider1 = serviceDescriptors.BuildServiceProvider();Microphone microphone1 = serviceProvider1.GetService<Microphone>();
}{ServiceCollection serviceDescriptors = new ServiceCollection();serviceDescriptors.AddTransient<Microphone>();ServiceProvider serviceProvider1 = serviceDescriptors.BuildServiceProvider();Microphone microphone1 = serviceProvider1.GetService<Microphone>();
}