Created
October 23, 2023 08:10
-
-
Save josejuan/af383a0e1b6c7c2341f043c1a32e751a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IService {} | |
public class ServiceA : IService {} | |
public class ServiceB : IService {} | |
// In your Startup.cs or ConfigureServices method | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddScoped<IService, ServiceA>(); | |
} | |
// Somewhere in your code where you want to switch the implementation | |
using (var scope = serviceProvider.CreateScope()) | |
{ | |
var scopedServices = scope.ServiceProvider; | |
var serviceDescriptor = new ServiceDescriptor(typeof(IService), typeof(ServiceB), ServiceLifetime.Scoped); | |
((ServiceCollection)scopedServices).Replace(serviceDescriptor); | |
var service = scopedServices.GetRequiredService<IService>(); | |
// Now 'service' will be an instance of ServiceB | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment