![](/img/trans.png)
[英]Why does this code give a "Possible null reference return" compiler warning?
[英]Possible null reference return warning in ConfigureServices()
这是我的代码 -
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices((context, services) =>
{
var cns = context.Configuration.GetConnectionString("db");
services.AddDbContext<DatabaseContext>(options => options.UseMySql(cns, ServerVersion.AutoDetect(cns)));
//Possible null reference return warning here-
services.AddScoped<IDatabaseContext>(provider => provider.GetService<DatabaseContext>());
services.AddScoped<CensusService>();
})
.Build();
要删除该警告,该行的正确写法应该是什么?
ServiceProviderServiceExtensions.GetService<T>
返回T?
如果T
是引用类型,它将成为可为空的引用类型,而注册需要一个不可为空的类型。
使用ServiceProviderServiceExtensions.GetRequiredService<T>
返回一个实例,如果没有T
类型的服务则抛出InvalidOperationException
:
services.AddScoped<IDatabaseContext>(provider =>
provider.GetRequiredService<DatabaseContext>());
但是在DbContext
注册的情况下,有AddDbContext
的重载允许拆分合同和实现(如 Julien 在评论中所建议的那样),因此如果您只需要通过接口解析上下文,您可以使用其中之一:
services.AddDbContext<IDatabaseContext, DatabaseContext>(options => ...));
有关的:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.