Xabaril / Esquio

Esquio is a Feature Toggle Library for .NET Developers.
Apache License 2.0
429 stars 49 forks source link

Use features to conditionally register services #132

Closed unaizorrilla closed 4 years ago

unaizorrilla commented 4 years ago

Add new IServiceCollection extensions to enable services depending on feature state, is like a factory but with some sugar to simplify developers code

unaizorrilla commented 4 years ago

Fixed on features/esquio31 and will be available on Esquio 3.1

        /// <summary>
        /// Add a new service depending on a feature state.
        /// </summary>
        /// <typeparam name="TService">The system type of the service.</typeparam>
        /// <param name="services">The <see cref="IServiceCollection"/> used.</param>
        /// <param name="featureName">The feature name to be evaluated.</param>
        /// <param name="featureEnabled">The factory used to create the service implementation when the feature is enabled.</param>
        /// <param name="featureDisabled">The factory used to create the service implementation when the feature is disabled.</param>
        /// <param name="serviceLifetime">The service lifetime to set.</param>
        /// <returns>The collection of configured services.</returns>
        public static IServiceCollection Add<TService>(this IServiceCollection services,
            string featureName,
            Func<IServiceProvider, object> featureEnabled,
            Func<IServiceProvider, object> featureDisabled,
            ServiceLifetime serviceLifetime = ServiceLifetime.Transient)
        {
            _ = featureName ?? throw new ArgumentNullException(nameof(featureName));
            _ = featureEnabled ?? throw new ArgumentNullException(nameof(featureEnabled));
            _ = featureDisabled ?? throw new ArgumentNullException(nameof(featureDisabled));

            var descriptor = new ServiceDescriptor(typeof(TService), serviceProvider =>
            {
                var featureService = serviceProvider.GetService<IFeatureService>();

                var enabled = featureService.IsEnabledAsync(featureName)
                    .GetAwaiter()
                    .GetResult();

                return enabled ? featureEnabled(serviceProvider) : featureDisabled(serviceProvider);
            }, serviceLifetime);

            services.Add(descriptor);

            return services;
        }
unaizorrilla commented 4 years ago

After a review on this feature we decide to remove from 3.1!

Adding services to container and blocking with IFeatureService.IsEnabledAsync could be a performance problem. And this scenario will be solved easly with a factory!

We try to add a sample of this scenario but remove this Add extension method!!