提问者:小点点

如何注入托管工人服务?


我有一个从默认的。NET核心模板创建的辅助服务。我有两个额外的服务我想运行,一个发出事件,另一个使用它。因此,理想情况下,它们都应该被注入到单个worker托管服务中。我怎么才能让这一切发生?我尝试了如下代码,但我得到了:System.InvalidOperationException:“在尝试激活”MessageQueueReceiver.Worker“时,无法解析类型”Receiver.IMessageReceiver“的服务。”

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddSingleton&ltIMessageReceiver, MessageReceiver>();
                    services.AddSingleton&ltIWebhookMessageForwarder, WebhookMessageForwarder>();
                    services.AddHostedService&ltWorker>();
                });
    }
    public class Worker : BackgroundService
    {
        private readonly ILogger _logger;
        private readonly IMessageReceiver _messageReceiver;
        private readonly IWebhookMessageForwarder _forwarder;

        public Worker(ILogger&ltWorker> logger, 
            IMessageReceiver messageReceiver, 
            IWebhookMessageForwarder forwarder)
        {
            _logger = logger;
            _messageReceiver = messageReceiver;
            _forwarder = forwarder;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _messageReceiver.MessageReceived += _forwarder.OnMessageReceived;
            _messageReceiver.RegisterHandlerAndReceiveMessages();

            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                await Task.Delay(TimeSpan.FromSeconds(60), stoppingToken);
            }
        }
    }

共1个答案

匿名用户

问题似乎是在初始化您的某个类。请检查Worker,Message Receiver和MessageForwarder类的constructor。

同样检查这一行,您正在创建接口的实例。

services.AddSingleton<IWebhookMessageForwarder, IWebhookMessageForwarder>()

我尝试了下面的代码,它工作了,它承载了一个BackgroundService。

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
       Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                services.AddSingleton<IMessageReceiver, MessageReceiver>();
                services.AddSingleton<IWebhookMessageForwarder, WebhookMessageForwarder>();
                services.AddHostedService<Worker>();
            });
}

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private readonly IMessageReceiver _messageReceiver;
    private readonly IWebhookMessageForwarder _forwarder;

    public Worker(IMessageReceiver messageReceiver,
        IWebhookMessageForwarder forwarder)
    {
        _messageReceiver = messageReceiver;
        _forwarder = forwarder;
    }

    public override Task StartAsync(CancellationToken cancellationToken)
    {
        return base.StartAsync(cancellationToken);
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            System.Console.WriteLine("Hello");
            await Task.Delay(TimeSpan.FromSeconds(60), stoppingToken);
        }
    }
}


public interface IWebhookMessageForwarder
{
}

public class WebhookMessageForwarder : IWebhookMessageForwarder
{
}

public interface IMessageReceiver
{
}

public class MessageReceiver : IMessageReceiver
{
}