Это консольное приложение .NET Core 2.0, использующее DI, как я могу передать параметры конструктору.
Классу RabbitMQPersistentConnection необходимо передать параметр на конструкторе
RabbitMQPersistentConnection (регистратор ILogger, IConnectionFactory connectionFactory, IEmailService emailService);
Мой экземпляр * 10091010 *
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;
}
}