Last active
January 24, 2026 07:56
-
-
Save vlapenkov/1ea1d17781f4b250e41a1a8099925f1f to your computer and use it in GitHub Desktop.
ConfigurableService.cs
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
| public static IServiceCollection Register<TService, TOptions>(this IServiceCollection services, | |
| Action<TOptions> optionsAction) | |
| where TService : class where TOptions : new() | |
| { | |
| services.AddScoped<TService>(provider => | |
| { | |
| var options = new TOptions(); | |
| optionsAction.Invoke(options); | |
| // Use ActivatorUtilities to create an instance, injecting dependencies | |
| var instance = ActivatorUtilities.CreateInstance<TService>(provider); | |
| if (instance is IConfigurableService<TOptions> service) | |
| { | |
| service.Configure(options); | |
| } | |
| return instance; | |
| }); | |
| return services; | |
| } | |
| public class ServiceOptions | |
| { | |
| public string Name { get; set; } | |
| public int Age { get; set; } | |
| } | |
| ublic interface IConfigurableService<TOptions> | |
| { | |
| void Configure(TOptions options); | |
| } | |
| public class Service1 : IConfigurableService<ServiceOptions> | |
| { | |
| public string Name { get; private set; } | |
| public int Age { get; private set; } | |
| public Service1(Service2 service2) | |
| { | |
| } | |
| public void Configure(ServiceOptions options) | |
| { | |
| Name = options.Name; | |
| Age = options.Age; | |
| } | |
| } | |
| // Регистрация | |
| services.Register<Service1, ServiceOptions>(options => | |
| { | |
| options.Name = "Service1"; | |
| options.Age = 1; | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment