dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.16k stars 4.71k forks source link

[API Proposal]: Add to ServiceCollectionDescriptorExtensions generic .Replace<T> method #64510

Open KSemenenko opened 2 years ago

KSemenenko commented 2 years ago

Background and motivation

For replacement implementation in TestHost I should do like this:

 services.RemoveAll<ISomeInterface>();
 services.AddSingleton<ISomeInterface, FakeImplementation>();

Or like this

services.Replace(new ServiceDescriptor(..... ));

So I thought, why not use the Replace method but found that it didn't exist.

API Proposal

namespace Microsoft.Extensions.DependencyInjection.Extensions
{
    public static class ServiceCollectionDescriptorExtensions
    {
        public static bool Replace(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> factory);
        public static bool Replace<TService>(this IServiceCollection services, Func<IServiceProvider, TService> factory);
        public static bool Replace<TService, TImplementation>(this IServiceCollection services);
    }
}

API Usage

 services.Replace<FakeImplementation>();
 services.Replace<ISomeInterface, FakeImplementation>();
 services.Replace<ISomeInterface>(f=> new FakeImplementation());

Alternative Designs

No response

Risks

The Replace method already exists, it's a new API, so I don't see any serious risks.

ghost commented 2 years ago

Tagging subscribers to this area: @dotnet/area-extensions-dependencyinjection See info in area-owners.md if you want to be subscribed.

Issue Details
### Background and motivation For replacement implementation in TestHost I should do like this: ``` cs services.RemoveAll(); services.AddSingleton< ISomeInterface, FakeImplementation>(); ``` Or like this ``` cs services.Replace(new ServiceDescriptor(..... )); ``` So I thought, why not use the Replace method but found that it didn't exist. ### API Proposal ```C# namespace Microsoft.Extensions.DependencyInjection.Extensions { public static class ServiceCollectionDescriptorExtensions { public static bool Replace(this IServiceCollection services, Type serviceType, Func factory); public static bool Replace(this IServiceCollection services, Func factory); public static bool Replace(this IServiceCollection services); } } ``` ### API Usage ``` cs services.Replace(); services.Replace(); services.Replace(f=> new FakeImplementation()); ``` ### Alternative Designs _No response_ ### Risks The Replace method already exists, it's a new API, so I don't see any serious risks.
Author: KSemenenko
Assignees: -
Labels: `api-suggestion`, `untriaged`, `area-Extensions-DependencyInjection`
Milestone: -
KSemenenko commented 2 years ago

If it's a good idea, I'm happy to implement it.

KSemenenko commented 6 months ago

I think lifetime should be the same, as you mention it’s for testing