Last active
December 23, 2024 20:25
-
-
Save gusarov/22a3af47260957198b516596a8aa23f8 to your computer and use it in GitHub Desktop.
DI Container service graph branches
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; | |
var serviceCollection = new ServiceCollection(); | |
serviceCollection.AddScoped<JsonConfigUpdater>(); | |
serviceCollection.AddScoped<JsonConfigUpdaterSettigns>(); | |
serviceCollection.AddSingleton<ConfigUpdaterManager>(); | |
var provider = serviceCollection.BuildServiceProvider(); | |
var manager = provider.GetRequiredService<ConfigUpdaterManager>(); | |
Console.WriteLine(manager._dsUpdater._settings.Name); | |
Console.WriteLine(manager._msUpdater._settings.Name); | |
class JsonConfigUpdaterSettigns | |
{ | |
public string Name { get; set; } | |
} | |
class JsonConfigUpdater | |
{ | |
public readonly JsonConfigUpdaterSettigns _settings; | |
public JsonConfigUpdater(JsonConfigUpdaterSettigns settings) | |
{ | |
_settings = settings; | |
} | |
} | |
class ConfigUpdaterManager | |
{ | |
public JsonConfigUpdater _msUpdater; | |
public JsonConfigUpdaterSettigns _msUpdaterSettings; | |
public JsonConfigUpdater _dsUpdater; | |
public JsonConfigUpdaterSettigns _dsUpdaterSettings; | |
public ConfigUpdaterManager(IServiceProvider serviceProvider) | |
{ | |
// MS | |
using (var scope = serviceProvider.CreateScope()) | |
{ | |
_msUpdater = scope.ServiceProvider.GetRequiredService<JsonConfigUpdater>(); | |
_msUpdaterSettings = scope.ServiceProvider.GetRequiredService<JsonConfigUpdaterSettigns>(); | |
_msUpdaterSettings.Name = "MS"; | |
} | |
// DS | |
using (var scope = serviceProvider.CreateScope()) | |
{ | |
_dsUpdater = scope.ServiceProvider.GetRequiredService<JsonConfigUpdater>(); | |
_dsUpdaterSettings = scope.ServiceProvider.GetRequiredService<JsonConfigUpdaterSettigns>(); | |
_dsUpdaterSettings.Name = "DS"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment