如何注入托管工人服务?

时间:2019-11-12 22:47:10

标签: c# asp.net-core .net-core worker

我有一个从默认.NET Core模板创建的工作程序服务。我还有两个我想运行的服务,一个服务发出一个事件,另一个服务消耗它。因此,理想情况下,它们两者都应注入到单个Worker托管服务中。我怎样才能做到这一点?我尝试了如下代码,但得到了:System.InvalidOperationException: 'Unable to resolve service for type 'Receiver.IMessageReceiver' while attempting to activate 'MessageQueueReceiver.Worker'.'

    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 _logger;
        private readonly IMessageReceiver _messageReceiver;
        private readonly IWebhookMessageForwarder _forwarder;

        public Worker(ILogger<Worker> 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 个答案:

答案 0 :(得分:1)

看起来问题出在初始化您的课程之一。请检查的建设者 Worker,Message Receiver和MessageForwarder类。

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

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