Rak*_*mar 6 c# dependency-injection azure-functions
我正在使用 Azure Function(v3),我可以在startup.cs 中使用 IWebJobsStartup 和 FunctionsStartup 注册依赖项。
但我们应该使用哪一个呢?
使用 IWebJobsStartup 注册依赖项
[assembly: WebJobsStartup(typeof(Startup))]
namespace Notifications.Receiver
{
    public class Startup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            builder.Services.AddTransient<IEventValidator, EventValidator>();
            builder.Services.AddTransient<IEventReceiverHandler, EventReceiverHandler>();
            builder.Services.AddTransient<IEventHandler<InvoiceResultDto,InvoiceMessageEvent>, InvoiceMessageEventHandler>();
            builder.Services.AddTransient<IEventHandler<InvoiceResultDto, InvoiceFileEvent>, InvoiceFileEventHandler>();
            builder.Services.AddSingleton<IMessageBusFactory, AzureServiceBusFactory>();
            builder.Services.Configure<KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });
        }
    }
}
我也可以使用 FunctionsStartup 注册相同的依赖项
[assembly: FunctionsStartup(typeof(Startup))]
namespace Notifications.Receiver
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddTransient<IEventValidator, EventValidator>();
            builder.Services.AddTransient<IEventReceiverHandler, EventReceiverHandler>();
            builder.Services.AddTransient<IEventHandler<InvoiceResultDto,InvoiceMessageEvent>, InvoiceMessageEventHandler>();
            builder.Services.AddTransient<IEventHandler<InvoiceResultDto, InvoiceFileEvent>, InvoiceFileEventHandler>();
            builder.Services.AddSingleton<IMessageBusFactory, AzureServiceBusFactory>();
            builder.Services.Configure<KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });
        }
    }
}
小智 6
AFAIK,在 Azure Functions 中,现在执行依赖项注入的首选方法是使用FunctionsStartup.
Configure(IWebJobsBuilder builder)是的,如果我们在Startup.csIWebJobsStartup类中实现该接口,我们就必须实现该方法。
而当前的 MSFT 文档表示 Startup 类继承自FunctionsStartup类,并且ConfigureMethod 也采用IFunctionsHostBuilder.
这个类似的线程解释了使用FunctionsStartup与IWebJobsStartup中读取请求上的 HTTP 标头的问题Azure Functions .NET Applications,并最终建议使用FunctionsStartup是更好的方法。