请参见下面的代码:
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控制台应用程序。
答案 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);
}