杨中科 .Net Core 笔记 DI 依赖注入2
ServiceCollection services = new ServiceCollection();//定义一个承放服务的集合
services.AddScoped<iGetRole, GetRole>();
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
var list = serviceProvider.GetServices(typeof(iGetRole));
//获取到所有注册iGetRole类的实现对象
foreach (var item in list)
{
}
}
var list = serviceProvider.GetServices(typeof(iGetRole));//如果获取不到 则返回null
var t = serviceProvider.GetRequiredService<iGetRole>();//如果获取不到 则抛出异常
DI注入方式
默认:构造函数注入;属性注入;
---------------------------------------------------------------------------------------------------------------------------------
自动注入示例:
public class MailKitService : IMailKitService
{
private readonly ILogService _logService;
private readonly IConfigService _configService;
public MailKitService(ILogService _logService, IConfigService _configService)
{
this._logService = _logService;
this._configService = _configService;
}
public void SendMail(string address, string copyAddress, string title, string content)
{
_logService.LogInfo($"发送地址:{address}");
throw new NotImplementedException();
}
}
ServiceCollection services = new ServiceCollection();
services.AddScoped<IConfigService, ConfigService>();
services.AddScoped<ILogService, LogService>();
services.AddScoped<IMailKitService, MailKitService>();
using (var provider = services.BuildServiceProvider())
{
var mailService = provider.GetRequiredService<IMailKitService>();
//实现IMailKitService服务的 MailKitService构造函数会自动被注入ConfigService、LogService值
mailService.SendMail("11","","","");
}
---------------------------------------------------------------------------------------------------------------------------------
自定义扩展方法,与扩展对象同命名空间,使用this,使用地方可以直接点出来。(必须是静态类)