I have a configuration where users could select what features they want to enable/disable (i.e service) - and depend on it, if the service marked as disabled then it won't be registered in the service collection, but, I'll get other tons of null reference exceptions that the instance of the service is null, but you could say just check depending on configuration (enabled/disabled) or check if service is null or not and then use it.
Code example
IConfiguration configuration = null; //the config (it's ok this is null for showcase)
var theOneOfTheServicesEnabled = configuration
.GetSection("Features:TheOnefTheServices")
.GetValue<bool>("IsEnabled");
if (theOneOfTheServicesEnabled)
{
serviceCollection.AddSingleton<TheOnefTheServices>();
}
//it's ok, the service may be registered.. but, what if the user wrote false?
// InvalidOperationException
var theOneOfTheServicesInstance = ServiceProvider.GetRequiredService<TheOnefTheServices>();
theOneOfTheServicesInstance.Use();
// or just
var theOneOfTheServicesInstance = ServiceProvider.GetService<TheOnefTheServices>();
if (theOneOfTheServicesInstance != null)
{
// then use it
theOneOfTheServicesInstance.Use();
}
// or
if (theOneOfTheServicesEnabled)
{
theOneOfTheServicesInstance.Use();
}
But, all the cases are looking bad! Because I need to check if the service is null or not, or if the user specified the false in the configuration. Note that these services are the classes and don't have an interface and are always used by the real instance.
Update
I already solved it, by just following the KISS principle, now just checking if the service is not null, lol :D Yet someone came up with a solution..