.net core DI,使用一个依赖项中的值来注册另一个依赖项

reg*_*ahn 0 .net c# dependency-injection .net-core asp.net-core

我正在使用.net核心2.1,并且我正在使用本机IoC容器注册服务并需要一个值来注册另一组服务

var hostBuilder = new HostBuilder()
    .ConfigureServices((hostContext, services) => 
    {
        services
        .AddSingleton<IFirstService, FirstService>()
        .AddMyServices(FirstService.MyProperty);
    });
Run Code Online (Sandbox Code Playgroud)

我在哪里AddMySerivces使用扩展IServiceCollection来注册其他依赖项

public static IServiceCollection AddMyServices(
    this IServiceCollection serviceCollection, string myProperty)
{
    // user myProperty here to register other things
}
Run Code Online (Sandbox Code Playgroud)

有什么好办法FirstService.MyProperty让它传入AddMyServices

juu*_*nas 6

怎么样:

public static IServiceCollection AddMyServices(this IServiceCollection serviceCollection)
{
    serviceCollection.AddTransient<ISomeService>(sp =>
    {
        var firstService = sp.GetRequiredService<IFirstService>() as FirstService;
        var firstProperty = firstService.FirstProperty;

        // Build an instance of ISomeService based on the property
    });
}
Run Code Online (Sandbox Code Playgroud)

这会将工厂注册为依赖于第一个服务的依赖项.当然,您需要为每项服务执行此操作:/

您还可以将属性添加到IFirstService接口,这样就不需要转换服务.