【发布时间】:2022-01-07 19:17:41
【问题描述】:
在使用来自单例的作用域时,我没有收到任何错误
根据下面的文章,我应该在启动服务后立即收到错误消息:
https://dotnetcoretutorials.com/2018/03/20/cannot-consume-scoped-service-from-singleton-a-lesson-in-asp-net-core-di-scopes/
依赖注册:
builder.Services.AddScoped<ILogger, AppLogs>();
builder.Services.AddSingleton<ICacheFactory>(x =>
{
string cacheConnectionString = "xyz";
return new CacheFactory(cacheConnectionString, x.GetService<ILogger>());
});
消耗:
public class Function1
{
private readonly ICacheFactory cacheProvider;
public Function1(ICacheFactory cacheProvider) {
this.cacheProvider = cacheProvider;
}
[FunctionName("Function1")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
var result = await this.cacheProvider.GetResultsAsync<IEnumerable<string>>("abc").ConfigureAwait(false);}
}
单例中的作用域注入何时会产生问题?
【问题讨论】:
-
了解Captive Dependencies的概念。
标签: asp.net-core dependency-injection singleton