We have a service based application in .net core which would run as a daemon in Linux environment. Everything is working as expected but i am having problem in handling dependency injection. Below is the code for reference
Program.cs
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Starting PreProcessor Application ");
try
{
ConfigParameters.LoadSettings(args);
}
catch (Exception ex)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine($"Error in setting config parameters {ex.Message}");
return;
}
IHost host = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddLogging();
services.AddHostedService<MainService>();
services.AddTransient<IMessageQueue, ActiveMQHandler>(x =>
{
return new ActiveMQHandler(ConfigParameters.Settings.MessageQueueAddress);
});
services.AddTransient<IMessageQueue, ActiveMQHandler>(x =>
{
return new ActiveMQHandler(ConfigParameters.Settings.MessageQueueAddress);
});
services.AddTransient<IMessageQueue, ActiveMQHandler>(x =>
{
return new ActiveMQHandler(ConfigParameters.Settings.MessageQueueAddress);
});
})
.Build();
await host.RunAsync();
}
}
Constructor for MainService looks like this
IApplicationLifetime appLifetime;
IConfiguration configuration;
PreProcessorQueueListener listener;
private string reason = "SHUTDOWN SIGNAL";
private IMessageQueue messageQueue;
private IMessageQueue messageQueueSL;
private IMessageQueue messageQueueSLProcess;
public MainService(IConfiguration configuration, IApplicationLifetime appLifetime, IMessageQueue messageQueue, IMessageQueue messageQueueSL, IMessageQueue messageQueueSLProcess)
{
this.configuration = configuration;
this.messageQueue = messageQueue;
this.messageQueueSL = messageQueueSL;
this.messageQueueSLProcess = messageQueueSLProcess;
this.appLifetime = appLifetime;
}
If you see in my MainService code i am passing three instances for IMessageQueue interface using constructor dependency injection. What i really want is based on a need in any part of the application i could grab a new instance of ActiveMQHandler class by passing IMessageQueue interface. Since i could not find a solution for this i am passing three instances (i am not happy with this solution) of IMessageQueue. If i need to use another instance of ActiveMQHandler class then i will have to pass fourth parameter as IMessageQueue interface in my MainService class.
What i am really looking for is use ServiceProvider (or something more elegant) and use that to get a new / singleton (based on how it is defined in Program.cs) instance of the class which implements the IMessageQueue interface.
An suggestions guys??