1

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.

1 Answer 1

2

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); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.