Skip to content

Instantly share code, notes, and snippets.

@josejuan
Created October 23, 2023 08:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josejuan/af383a0e1b6c7c2341f043c1a32e751a to your computer and use it in GitHub Desktop.
Save josejuan/af383a0e1b6c7c2341f043c1a32e751a to your computer and use it in GitHub Desktop.
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