[英]Azure Functions Dependency Injection - Registering Custom Services
I'm trying to do DI in Azure Functions V2 with my service but even after reading the documentation I'm not understanding how to register a service with parameters.我正在尝试使用我的服务在 Azure Functions V2 中执行 DI,但即使阅读了文档,我也不了解如何使用参数注册服务。
In the example below I want to use the built-in Logger and the DB context within CustomService
and the CustomService
within SpecialService
.在下面的示例中,我想在
CustomService
中使用内置的 Logger 和 DB 上下文,在SpecialService
中使用CustomService
。 These are in the constructors of the respective services, ie CustomService(IMyContext context, ILogger logger)
and SpecialService(ICustomService customService)
.这些在各自服务的构造函数中,即
CustomService(IMyContext context, ILogger logger)
和SpecialService(ICustomService customService)
。
Startup.cs:启动.cs:
[assembly: FunctionsStartup(typeof(Startup))]
namespace AzFunction.IoC
{
class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddLogging();
var connectionString = "test-conn-string";
var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
builder.Services.AddDbContext<MyDbContext>(
options => options.UseSqlServer(connectionString));
builder.Services.AddScoped<ICustomService, CustomService>();
builder.Services.AddScoped<ISpecialSerivce, SpecialService>();
}
}
}
It compiles and and hits the breakpoints with in startup.cs
but does not seem to be able to find the services that are registered.它在
startup.cs
中编译并命中断点,但似乎无法找到已注册的服务。
The error:错误:
Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'customService' to type ICustomService.
Microsoft.Azure.WebJobs.Host:无法将参数“customService”绑定到类型 ICustomService。 Make sure the parameter Type is supported by the binding.
确保绑定支持参数类型。
I was trying to inject into the Azure functions parameters instead of the constructor, here is the correct way:我试图注入 Azure 函数参数而不是构造函数,这是正确的方法:
public class GreatClass
{
private ICustomService _customService;
public GreatClass(ICustomService customService)
{
_customService = customService;
}
[FunctionName("MyFunc")]
public async Task Run([TimerTrigger("%RunFrequency%", RunOnStartup = true)]TimerInfo myTimer,
// ICustomService customService, // Incorrect!
ILogger log)
{
//Logic
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.