.NetCore IOC容器练习

2021-03-07 06:28

阅读:622

标签:style   new   imp   ddt   sof   builds   声明   ioc   msde   

Microsoft.Extensions.DependencyInjection

//添加Nuget包Microsoft.Extensions.DependencyInjection
var serviceCollection = new ServiceCollection();
serviceCollection.AddTransient();
serviceCollection.AddSingleton();
serviceCollection.AddScoped();

var serviceProvider = serviceCollection.BuildServiceProvider();
serviceProvider.GetService().SayHello();
foreach (var item in serviceProvider.GetServices())
{
    item.SayHello();
}
serviceProvider.GetService().SayHello();
foreach (var item in serviceProvider.GetServices())
{
    item.SayHello();
}
//仅注册过的方可拿到,此处MyClass未注册,GetService为Null,抛异常
serviceProvider.GetService().SayHello();
//仅注册过的方可拿到,此处MyClass未注册,GetRequiredService提示未注册,抛异常
serviceProvider.GetRequiredService().SayHello();

 

Castle.Windsor:

//需要添加Nuget包:Castle.Windsor.MsDependencyInjection和Castle.Core
//需要添加引用:Castle.Windsor和Castle.Windsor.MsDependencyInjection
//创建容器
Castle.Windsor.WindsorContainer container = new Castle.Windsor.WindsorContainer();
//旧版可以适用如下注册container.AddComponent();
//容器注册组件,并且管理组件的生命周期
container.Register(Component.For().ImplementedBy().LifestyleSingleton().Named("MyClass"));
container.Register(Component.For().ImplementedBy().LifestyleScoped().Named("YouClass"));
container.Register(Component.For().ImplementedBy().LifestyleTransient().Named("TheyClass"));
container.BeginScope();
//组件激活,拿到组件实例
container.Resolve("MyClass").SayHello();
//声明周期为Scoped的,必须执行BeginScoped后开始调用,在下一个BeginScope调用之前,只实例化一次
container.BeginScope();
foreach (var item in container.ResolveAll())
{
    item.SayHello();
}
container.Resolve("YouClass").SayHello();
//声明周期为Scoped的,必须执行BeginScoped后开始调用,在下一个BeginScope调用之前,只实例化一次
container.BeginScope();
foreach (var item in container.ResolveAll())
{
    item.SayHello();
}
//容器释放
container.Dispose();

 

.NetCore IOC容器练习

标签:style   new   imp   ddt   sof   builds   声明   ioc   msde   

原文地址:https://www.cnblogs.com/lcawen/p/12888580.html


评论


亲,登录后才可以留言!