废话不说,直接代码
//注入 按单例模式注入RabbitMQ的ConnectionFactory { var mqCfg = context.Configuration.GetSection("RabbitMQ").Get<RabbitMQCfg>(); var cf = new ConnectionFactory() { HostName = mqCfg.HostName, Port = mqCfg.Port, UserName = mqCfg.UserName, Password = mqCfg.Password, VirtualHost = mqCfg.VirtualHost, }; RabbitMQTools.Init(cf); services.AddSingleton(cf); } { var mqCfg = context.Configuration.GetSection("RabbitMQLogger").Get<MyRabbitMQLoggerProviderOptions>(); var cf = new ConnectionFactory() { HostName = mqCfg.HostName, Port = mqCfg.Port, UserName = mqCfg.UserName, Password = mqCfg.Password, VirtualHost = mqCfg.VirtualHost, }; RabbitMQTools.Init(cf); services.AddSingleton(cf); }
获取方式也很简单,主要有两种
1.构造中接收
/// <summary></summary> public TimedBackgroundService(IEnumerable<ConnectionFactory> svs) { }
2.GetServices接收
using (var sp = logbuild.Services.BuildServiceProvider()) { var mqFact2 = sp.GetServices<ConnectionFactory>(); var mqFact = mqFact2.First(d => d.VirtualHost.EqualIgnoreCase("log")); var option = sp.GetService<IConfiguration>().GetSection("RabbitMQLogger").Get<MyRabbitMQLoggerProviderOptions>(); logbuild.AddMyRabbitMQLog(mqFact, option); }
还可以使用AspectCore的属性注入接收
[AspectCore.DependencyInjection.FromServiceContext] private IEnumerable<ConnectionFactory> svc { get; set; }
理论上支持 AddSingleton、AddTransient、AddScoped
over