Type ServiceSettings? cannot be used as type parameter 'TService' in the generic type or method 'AddSingleton<TService>'

Viewed 20

I have in .net 5 application in startup.cs:

ServiceSettings serviceSettings = new ServiceSettings();            
Configuration.GetSection(ServiceSettings.AppSettingsJsonSectionName).Bind(serviceSettings);
services.AddSingleton(serviceSettings);
services.AddSingleton((ServiceSettingsBase)serviceSettings);

public sealed class ServiceSettings : ServiceSettingsBase
{
    ...
}
public abstract class ServiceSettingsBase
{
    ...
}

And all works good, no warnings no exceptions. Now I have new app in .net 6, a I want use the sam code in program.cs. I changed services.AddSingleton to builder.Services.AddSingleton but I have warning:

The type 'ServiceSettings?' cannot be used as type parameter 'TService' in the generic type or method '...AddSingleton(...)'. Nullablity of type argument 'ServiceSettings' doesn't match 'class' constraint.

Whats wrong? Whats changed? Whats should I do?

///Edit

I would like to add that I migrated the first project created in .net 5 to .net 6 and there is no such message either (the same version of VS2022). But from what I can see maybe there is some rule in VS that warns against null values, because adding an 'if serviceSettings != null' condition made the message disappear.

0 Answers
Related