w0051977
w0051977

Reputation: 15807

AddTransient with a dependancy

Please see the code below:

var services = new ServiceCollection()

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

This works as expected. Is it possible to do something like this:

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);
}

What is the proper way of doing this? It is a .NET Core console app.

Upvotes: 1

Views: 73

Answers (1)

DavidG
DavidG

Reputation: 118937

You are an overload of the AddTransient method which gives you the sp parameter which is an instance of IServiceProvider:

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);
}

Upvotes: 2

Related Questions