1 认识依赖注册 (what how why)
why 帮助管理 ,类与类之间的依赖关系 。借助di框架,可以经松管理类之间的依赖。确保可维护可扩展。.net 提供了,生命周期 管理的核心。
how DependencyInjection.Abstration 和 DependencyInjject > 组件只需要依赖抽象接口,使用时,注入具体的。 意味着未来使用,可以根据具体情况替换。 核心类型
核心类型
IserviceCollection 服务的注册
ServiceDescripotr 服务解释
IServiceProvider 具体空器
IServiceScope 容器的子容器生命周期
生命周期
singletone 单例
scoped 作用域,(web 时,一次请求)
transient 瞬时
Whom
2 .net core 提供的3个生命周期 最简单的基础实现
2.1 准备3 个服务类。
//MyScopedService.cs
namespace n5.Service
{
interface IScopedService { }
public class MyScopedService : IScopedService
{
public void debug()
{
Console.WriteLine("MyScopedService");
}
}
}
//MySingletoeService.cs ...
//MyTransientService.cs ...
2.2 进行注入。
//注册服务 。 program.cs
#region 依赖注入
builder.Services.AddSingleton<ISingletoeService, MySingletoeService>();
builder.Services.AddScoped<IScopedService, MyScopedService>();
builder.Services.AddTransient<ITransientService, MyTransientService>();
#endregion 依赖注入。
注意细节 ISingletoeService要public
2.3 调用查看。
[HttpGet]
public int GetService(
[FromServices] ISingletoeService sin1,
[FromServices] ISingletoeService sin2,
[FromServices] IScopedService sco1,
[FromServices] IScopedService sco2,
[FromServices] ITransicentService t1,
[FromServices] ITransicentService t2
)
{
Console.WriteLine("GetService--------------------------");
Console.WriteLine($" sin1 : {sin1.GetHashCode()}");
Console.WriteLine($" sin2 : {sin2.GetHashCode()}");
Console.WriteLine($" sco1 : {sco1.GetHashCode()}");
Console.WriteLine($" sco2 : {sco2.GetHashCode()}");
Console.WriteLine($" t1 : {t1.GetHashCode()}");
Console.WriteLine($" t2 : {t2.GetHashCode()}");
return 1;
}
刷新两次效果 。
singletone 不变, scoped 每次请求时一致,transicent 即用即销毁。
新手注意。 [FromServices] ISingletoeService sin1, 不能用 [FromServices] MySingletoeService sin1,
注意定义接口为public
3 一些其它注册。 (多玩下,练练手感,没必要记), 记得越多,脑子越晕。用的时候,找到对应的场景,查下api 即可。
直接注册实例。
builder.Services.AddSingleton<IOrderService>(new MyOrderService());
//控制器添加代码 。 先这么跑出来,看效果 。
[HttpGet]
public void GetServiceList([FromServices] IEnumerable<IOrderService> s)
{
foreach(var item in s)
{
Console.WriteLine($"获取到服务实例 {item.ToString()}: {item.GetHashCode()}");
}
}
再注册些其它的。
如果直接用的话,又有多个不同的实现的话,则出来最后一个。
public void GetServiceList(
[FromServices] IOrderService s1)
// [FromServices] IEnumerable<IOrderService> s)
{
Console.WriteLine($" s1 : {s1.ToString()} {s1.GetHashCode()}");
/*
foreach(var item in s)
{
Console.WriteLine($"获取到服务实例 {item.ToString()}: {item.GetHashCode()}");
}
*/
}
一些其它的。 TryAddSingleton 仅注册一次。 TryAddEnumrable 同一实现的,仅注册一个。 replace [把第一个实现替换] remove
注册泛型
注意调整第一个入参数 typeof ,在使用时,给具体的。