Created
January 11, 2024 09:41
-
-
Save Ilchert/85256bd9be8283f2bd75596ae7136361 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.Extensions.Options; | |
var services = new ServiceCollection(); | |
services.AddSingleton<RootService>(); | |
services.AddSingleton<IService, RootService>(); | |
PluginImplementation.Configure(services); | |
using var rootSp = services.BuildServiceProvider(); | |
var pluginRegistration = rootSp.GetRequiredService<IOptionsMonitor<PluginRegistration>>() | |
.Get(PluginImplementation.Name); | |
var pluginServices = new ServiceCollection(); | |
using var scope = rootSp.CreateScope(); | |
pluginRegistration.Configure(scope.ServiceProvider, pluginServices); | |
using var pluginSp = pluginServices.BuildServiceProvider(); | |
var fromRoot = pluginSp.GetRequiredService<RootService>(); | |
Console.WriteLine(fromRoot); // RootService | |
var fromPlugin = pluginSp.GetRequiredService<IService>(); | |
Console.WriteLine(fromPlugin); //PluginOverride | |
interface IService { } | |
class RootService : IService { } | |
class PluginOverride : IService { } | |
interface IPlugin { } | |
class PluginImplementation : IPlugin | |
{ | |
public const string Name = nameof(PluginImplementation); | |
public static void Configure(ServiceCollection rootServices) | |
{ | |
rootServices.Configure<PluginRegistration>(Name, o => o.Configure = static (sp, services) => | |
{ | |
services.AddSingleton<IService, PluginOverride>(); | |
services.AddSingleton(_ => sp.GetRequiredService<RootService>()); | |
}); | |
} | |
} | |
class PluginRegistration | |
{ | |
public Action<IServiceProvider, ServiceCollection> Configure = delegate { }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment