具有依赖关系的AddTransient

时间:2019-03-18 12:25:23

标签: c# asp.net-core

请参见下面的代码:

var services = new ServiceCollection()

.AddTransient<OtherService, OtherService>()
.AddTransient<ProductService, ProductService>(sp =>
{
    Guid Id = Guid.Parse(configuration["Id"]);
        return new Product(Id, new OtherService());
}

这按预期工作。是否可以做这样的事情:

var services = new ServiceCollection()

.AddTransient<OtherService, OtherService>()
.AddTransient<ProductService, ProductService>(sp =>
{
    var otherService = GetService<OtherService>();
    Guid Id = Guid.Parse(configuration["Id"]);
        return new Product(Id, otherService);
}

执行此操作的正确方法是什么?这是一个.NET Core控制台应用程序。

1 个答案:

答案 0 :(得分:2)

您是AddTransient方法的重载,该方法为您提供了IServiceProvider实例的sp参数:

var services = new ServiceCollection()

.AddTransient<OtherService, OtherService>()
.AddTransient<ProductService, ProductService>(sp =>
{
    var otherService = sp.GetService<OtherService>();
                     //^^ <---this
    Guid Id = Guid.Parse(configuration["Id"]);
    return new Product(Id, otherService);
}