jason-roberts / FeatureToggle

Simple, reliable feature toggles in .NET
http://dontcodetired.com/blog/?tag=/featuretoggle
Apache License 2.0
689 stars 111 forks source link

Configuring custom IBooleanToggleValueProvider with dependency injection #154

Open DKotoski opened 6 years ago

DKotoski commented 6 years ago

Hello, In our startup we have something like:

IServiceCollection AddFeatureToggle(this IServiceCollection service, IConfigurationRoot configuration)
{
     var provider = new CustomBooleanToggleValueProvider(configuration);
     service.AddSingleton<ICustomFeatureToggle>(new CustomFeatureToggle() { ToggleValueProvider = provider });
     return service;
}

The CustomBooleanToggleValueProvider inherits IBooleanToggleValueProvider When I go to the controller and check if feature is toggled with featureToggle.FeatureEnabled it throws an error. I have noticed that the ToggleValueProvider is still AppSettingsProvider instead of the CustomBooleanToggleValueProvider .

The .AddSingleton extension is from the package Microsoft.Extensions.DependencyInjection

DKotoski commented 6 years ago

I found a workaround with this. I made a class that Inherits SimpleFeatureToggle but has a constructor that takes the IBooleanToggleValueProvider and sets it to ToggleValueProvider when constructing and then the CustomFeatureToggle inherits that instead of SimpleSkillProvider. After the change the DI looks like this

public static IServiceCollection AddFeatureToggle(this IServiceCollection service, IConfigurationRoot configuration)
        {
         var provider = new CustomBooleanToggleValueProvider(configuration);
         service
                .AddSingleton<FeatureToggle.IBooleanToggleValueProvider>(new CustomBooleanToggleValueProvider(configuration))
                .AddSingleton<ICustomFeatureToggle>(new CustomFeatureToggle(provider));

            return service;
        }

While this is a solution that works as needed can you please look into how the problem is caused. We suspect that it is something that is caused by the Microsoft.Extensions.DependencyInjection 2.0.0

jason-roberts commented 6 years ago

Hi @DKotoski - thanks for creating an issue for this, can you please provide the error and stacktrace you were getting - thanks :)

DKotoski commented 6 years ago

I unfortunately am not able reproduce it soon because that code come and went. If I find some time ill go back trough git history to that moment and send you the exact message. But the error is something about not being able to find the key. It was looking for "FeatureToggle:CustomFeatureToggle" but it was expected to look for "FeatureToggle.CustomFeatureToggle". It was definitely caused from the dependency injection not being able to inject the singleton new CustomFeatureToggle() { ToggleValueProvider = provider } Insdead of creating a feature toggle with the custom provider it generated it the same as would do new SimpleFeatureToggle()