[英]Possible null reference return warning in ConfigureServices()
Here is my code -这是我的代码 -
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();
To remove that warning, what should be the right way to write the line?要删除该警告,该行的正确写法应该是什么?
ServiceProviderServiceExtensions.GetService<T>
returns T?
ServiceProviderServiceExtensions.GetService<T>
返回T?
which will become nullable reference type if T
is a reference type, while the registration requires a non-nullable one.如果
T
是引用类型,它将成为可为空的引用类型,而注册需要一个不可为空的类型。
Use ServiceProviderServiceExtensions.GetRequiredService<T>
which returns an instance or throws InvalidOperationException
if there is no service of type T
:使用
ServiceProviderServiceExtensions.GetRequiredService<T>
返回一个实例,如果没有T
类型的服务则抛出InvalidOperationException
:
services.AddScoped<IDatabaseContext>(provider =>
provider.GetRequiredService<DatabaseContext>());
But in case of DbContext
registration there are overloads of AddDbContext
allowing to split the contract and implementation (as suggested by Julien in the comments), so if you need to resolve context only via the interface you can use one of those:但是在
DbContext
注册的情况下,有AddDbContext
的重载允许拆分合同和实现(如 Julien 在评论中所建议的那样),因此如果您只需要通过接口解析上下文,您可以使用其中之一:
services.AddDbContext<IDatabaseContext, DatabaseContext>(options => ...));
Related:有关的:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.