我目前正在使用带有内置DI的Azure Functions(v3),并且一切正常。但是,我不需要在运行时切换服务,而是想使用“穷人DI”,这为我提供了更好的编译保证。
public class Function1
{
private ExampleService _exampleService;
public Function1(ExampleService service)
{
this._exampleService = service;
}
[FunctionName("Function1")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
_exampleService.Foo();
}
}
// Startup.cs
builder.Services.AddSingleton((s) => {
return new ExampleService();
});
但是,如果我不想使用启动生成器,而是在请求进入时自己实例化Function1
类,这可能吗?
答案 0 :(得分:0)
穷人DI的最相似方法应如下所示:
public class Function1
{
private ExampleService _exampleService;
public Function1(ExampleService service = null)
{
this._exampleService = service ?? new ExampleService();
}
[FunctionName("Function1")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
_exampleService.Foo();
}
}
然后注释掉Startup.cs
中下面的代码:
builder.Services.AddSingleton((s) => {
return new ExampleService();
});