存根/模拟服务取决于配置

问题描述 投票:0回答:0

我有一个配置,用户可以在其中选择他们想要启用/禁用的功能(即服务)——并依赖它,如果服务标记为禁用,那么它不会在服务集合中注册,但是,我会得到其他大量空引用异常,表明服务实例为空,但您可以说只是根据配置(启用/禁用)进行检查,或者检查服务是否为空,然后使用它。

代码示例

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();
}

但是,所有的案子看起来都很糟糕!因为我需要检查服务是否为空,或者用户是否在配置中指定了 false。请注意,这些服务是类,没有接口,始终由真实实例使用。

c# service configuration mocking servicecollection
© www.soinside.com 2019 - 2024. All rights reserved.