简体   繁体   English

关于如何在 .NET 5.0 Worker 服务中使用 DI 最好地注册 EventGridClient 的指南

[英]Guidance on how to best register the EventGridClient with DI in a .NET 5.0 Worker Service

I'm using the EventGridClient from the Microsoft.Azure.EventGrid NuGet package to publish events to an Azure Event Grid Topic. I'm using the EventGridClient from the Microsoft.Azure.EventGrid NuGet package to publish events to an Azure Event Grid Topic. I understand that worker services are registered with singleton lifetime.我了解工作人员服务在 singleton 生命周期内注册。 I'm looking for guidance on how to best register the EventGridClient with the DI container in a worker service?我正在寻找有关如何在工作人员服务中使用 DI 容器最好地注册 EventGridClient 的指导? I'm using a .NET 5.0 worker hosted in a windows services.我正在使用托管在 windows 服务中的 .NET 5.0 工作人员。

DI registration (not sure if I've done the right thing here): DI注册(不确定我是否在这里做对了):

Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureServices((hostContext, services) =>
{
    services.AddSingleton(new EventGridClient(new TopicCredentials("topicKey"), // proxy auth
        new HttpClientHandler {DefaultProxyCredentials = CredentialCache.DefaultCredentials}));
    services.AddHostedService<Worker>();

})
.Build()
.Run();

Worker implementation:工人实施:

public class Worker : BackgroundService
{
    private readonly EventGridClient client;
    private readonly ILogger<Worker> logger;

    public Worker(EventGridClient client, ILogger<Worker> logger)
    {
        this.client = client;
        this.logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var events = new List<EventGridEvent>();

            await client.PublishEventsAsync("topicHostname", events, stoppingToken);

            logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            await Task.Delay(1000, stoppingToken);
        }
    }
}

Any guidance is highly appreciated.非常感谢任何指导。

I received an answer from Microsoft on their Q & A site which i'm pasting here in case someone else faces the same question.我在他们的问答网站上收到了微软的回答,我将其粘贴在这里,以防其他人面临同样的问题。

While your DI registration is technically fine and yes, it should be singleton as it involves http connection ( refer Improper Instantiation antipattern for details ), you can make it nicer and testable by registering the interface IEventGridClient against EventGridClient and inject IEventGridClient instead.虽然您的 DI 注册在技术上很好,是的,它应该是 singleton,因为它涉及 http 连接( 有关详细信息,请参阅不正确的实例化反模式),您可以通过针对EventGridClient IEventGridClient注入 IEventGridClient 来使其更好和可测试。

//...
.ConfigureServices((hostContext, services) =>
 {
     services.AddSingleton<IEventGridClient>(new EventGridClient(new TopicCredentials("topicKey"), // proxy auth
         new HttpClientHandler {DefaultProxyCredentials = CredentialCache.DefaultCredentials}));
     services.AddHostedService<Worker>();
    
 })

... ...

private readonly IEventGridClient client;
     private readonly ILogger<Worker> logger;
    
     public Worker(IEventGridClient client, ILogger<Worker> logger)
     {
         this.client = client;
         this.logger = logger;
     }

But note that since PublishEventsAsync is an extension method of IEventGridClient, if you write unit test for your code and inject a mock of IEventGridClient, remember to mock setup the method PublishEventsWithHttpMessages of IEventGridClient so that your test does not make a real call to event grid.但请注意,由于 PublishEventsAsync 是 IEventGridClient 的扩展方法,如果您为代码编写单元测试并注入 IEventGridClient 的模拟,请记住模拟设置PublishEventsWithHttpMessages的 PublishEventsWithHttpMessages 方法,以便您的测试不会真正调用事件网格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM