这是.NET Core 2.0控制台应用程序,使用DI如何将参数传递给构造函数。
RabbitMQPersistentConnection类需要在构造函数上传递参数
RabbitMQPersistentConnection(ILogger logger,IConnectionFactory connectionFactory,IEmailService emailService);
我的实例
var _emailService = sp.GetRequiredService();
将其初始化为服务时无法正常工作
Program.cs
public static class Program
{
public static async Task Main(string[] args)
{
// get App settings
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
//Initilize Service Collection
#region Initilize Service Collection
var serviceProvider = new ServiceCollection()
.AddLogging()
.AddEntityFrameworkSqlServer().AddDbContext<EmailDBContext>(option => option.UseSqlServer(configuration.GetConnectionString("connection_string")))
.AddSingleton<IEmailConfiguration>(configuration.GetSection("EmailConfiguration").Get<EmailConfiguration>())
.AddScoped<ISMTPService, SMTPService>()
.AddScoped<IEmailService, EmailService>()
.BuildServiceProvider();
#endregion
.ConfigureServices((hostContext, services) =>
{
services.AddLogging();
services.AddHostedService<LifetimeEventsHostedService>();
services.AddHostedService<TimedHostedService>();
services.AddEntityFrameworkSqlServer();
services.AddScoped<IRabbitMQPersistentConnection, RabbitMQPersistentConnection>(sp =>
{
var logger = sp.GetRequiredService<ILogger<RabbitMQPersistentConnection>>();
var _emailService = sp.GetRequiredService<IEmailService>(); // Not Working. :(
var _rabbitMQConfiguration = configuration.GetSection("RabbitMQConfiguration").Get<RabbitMQConfiguration>();
var factory = new ConnectionFactory()
{
HostName = _rabbitMQConfiguration.EventBusConnection
};
if (!string.IsNullOrEmpty(_rabbitMQConfiguration.EventBusUserName))
{
factory.UserName = _rabbitMQConfiguration.EventBusUserName;
}
if (!string.IsNullOrEmpty(_rabbitMQConfiguration.EventBusPassword))
{
factory.Password = _rabbitMQConfiguration.EventBusPassword;
}
return new RabbitMQPersistentConnection(logger, factory, _emailService);
});
})
.Build();
await host.RunAsync();
}
}
RabbitMQPersistentConnection.cs
public class RabbitMQPersistentConnection : IRabbitMQPersistentConnection
{
private readonly IConnectionFactory _connectionFactory;
EventBusRabbitMQ _eventBusRabbitMQ;
IConnection _connection;
IEmailService _emailService;
private readonly ILogger _logger;
bool _disposed;
public RabbitMQPersistentConnection(ILogger<RabbitMQPersistentConnection> logger, IConnectionFactory connectionFactory, IEmailService emailService)
{
_connectionFactory = connectionFactory ?? throw new ArgumentNullException(nameof(connectionFactory));
_emailService = emailService;
_logger = logger;
}
}
答案 0 :(得分:3)
您正在“ Initiilize Service Collection”区域中创建自己的IServiceProvider
,该区域是IServiceProvider
的不同实例,与您在此处使用的实例不同:
var _emailService = sp.GetRequiredService<IEmailService>();
您在您所在地区所做的注册只是被丢弃。为了解决这个问题,您可以将这些注册信息放入您的HostBuilder.ConfigureServices
回调函数中:
.ConfigureServices((hostContext, services) =>
{
services.AddLogging();
services.AddHostedService<LifetimeEventsHostedService>();
services.AddHostedService<TimedHostedService>();
services.AddEntityFrameworkSqlServer();
services.AddDbContext<EmailDBContext>(option => option.UseSqlServer(configuration.GetConnectionString("connection_string")));
services.AddSingleton<IEmailConfiguration>(configuration.GetSection("EmailConfiguration").Get<EmailConfiguration>());
services.AddScoped<ISMTPService, SMTPService>();
services.AddScoped<IEmailService, EmailService>();
services.AddScoped<IRabbitMQPersistentConnection, RabbitMQPersistentConnection>(sp =>
{
var logger = sp.GetRequiredService<ILogger<RabbitMQPersistentConnection>>();
var _emailService = sp.GetRequiredService<IEmailService>();
var _rabbitMQConfiguration = configuration.GetSection("RabbitMQConfiguration").Get<RabbitMQConfiguration>();
var factory = new ConnectionFactory()
{
HostName = _rabbitMQConfiguration.EventBusConnection
};
if (!string.IsNullOrEmpty(_rabbitMQConfiguration.EventBusUserName))
{
factory.UserName = _rabbitMQConfiguration.EventBusUserName;
}
if (!string.IsNullOrEmpty(_rabbitMQConfiguration.EventBusPassword))
{
factory.Password = _rabbitMQConfiguration.EventBusPassword;
}
return new RabbitMQPersistentConnection(logger, factory, _emailService);
});
})