Home > Net >  Possible null reference return warning in ConfigureServices()
Possible null reference return warning in ConfigureServices()

Time:11-14

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?

CodePudding user response:

ServiceProviderServiceExtensions.GetService<T> returns T? which will become nullable reference type if T is a reference type, while the registration requires a non-nullable one.

Use ServiceProviderServiceExtensions.GetRequiredService<T> which returns an instance or throws InvalidOperationException if there is no service of type T:

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:

services.AddDbContext<IDatabaseContext, DatabaseContext>(options => ...));

Related:

  • Related