在 .NET Core 服务应用程序中使用依赖注入 [英] Using Dependency Injection in .NET Core Service application

查看:32
本文介绍了在 .NET Core 服务应用程序中使用依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在 .net 核心中有一个基于服务的应用程序,它将在 Linux 环境中作为守护程序运行.一切都按预期工作,但我在处理依赖注入时遇到问题.下面是代码供参考

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

程序.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();
    }
}

MainService 的构造函数看起来像这样

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;
    }

如果您在我的 MainService 代码中看到,我正在使用构造函数依赖项注入为 IMessageQueue 接口传递三个实例.我真正想要的是基于应用程序任何部分的需求,我可以通过传递 IMessageQueue 接口来获取 ActiveMQHandler 类的新实例.由于我找不到解决方案,因此我传递了 IMessageQueue 的三个实例(我对这个解决方案不满意).如果我需要使用 ActiveMQHandler 类的另一个实例,那么我必须在我的 MainService 类中将第四个参数作为 IMessageQueue 接口传递.

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.

我真正想要的是使用 ServiceProvider(或更优雅的东西)并使用它来获得一个新的/单例(基于它在 Program.cs 中的定义)code>) 实现 IMessageQueue 接口的类的实例.

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.

有什么建议吗??

推荐答案

只需将构造函数更改为包含 IEnumerable.它应该为您提供所有已注册 IMessageQueue 实现者的列表.

Just change the constructor to contain IEnumerable<IMessageQueue>. It should give you a list of all registered IMessageQueue implementers.

我个人不喜欢在我的类中依赖 IApplicationLifetime 或 IServiceProvider.这有点像 ServiceLocator 反模式.

Personally I do not like taking on dependencies on IApplicationLifetime or IServiceProvider in my classes. This is a bit like the ServiceLocator anti-pattern.

这篇关于在 .NET Core 服务应用程序中使用依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆