I have some feature toggles that I include in my .NET application which uses StructureMap. I want to register the feature toggles for two purposes.
- Display current state of all
IFeatureson a diagnostic page. - Use certain instances in constructors of services that rely on given
IFeatureimplementations
Here is my setup. What I’m wondering is, am I doing this right? Is there a better way I could be doing it?
class HotNewFeature : IFeature { ... }
class ServiceThatUsesFeature
{
public ServiceThatUsesFeature(HotNewFeature hotNewFeature) { ... }
}
// Type registry setup
For<HotNewFeature>().Singleton().Use<HotNewFeature>();
For<IFeature>().Singleton().Add(c => c.GetInstance<HotNewFeature>);
For<ServiceThatUsesFeature>().Singleton().Use<ServiceThatUsesFeature>());
// Get all instances on the diagnostics page:
IEnumerable<IFeature> features = ServiceLocator.Current.GetAllInstances<IFeature>();
I expect that on the diagnostic page, features would in this case contain an IEnumerable with a single element, the instance of HotNewFeature.
Use the
Scanfeature to register all types that implement IFeature. That will satisfy your first need, to display a list on the Diagnostics page.If a service needs a specific implementation, it should declare the specific type it needs (
HotNewFeature) instead of the interface (IFeature) in the constructor. You have done this correctly in your example. At that point you do not need to do anything more in StructureMap. If you requestServiceThatUsersFeaturefrom StructureMap, and it relies on a concrete class (HotNewFeature), StructureMap will know how to instantiate that concrete class.