.NET Core DI, ways of passing parameters to constructor

  • A+
Category:Languages

Having the following service constructor

public class Service : IService {      public Service(IOtherService service1, IAnotherOne service2, string arg)      {       } } 

What are the choices of passing the parameters using .NET Core IOC mechanism

_serviceCollection.AddSingleton<IOtherService , OtherService>(); _serviceCollection.AddSingleton<IAnotherOne , AnotherOne>(); _serviceCollection.AddSingleton<IService>(x=>new Service( _serviceCollection.BuildServiceProvider().GetService<IOtherService>(), _serviceCollection.BuildServiceProvider().GetService<IAnotherOne >(), "" )); 

Is there any other way ?

 


The expression parameter (x in this case), of the factory delegate is a IServiceProvider.

Use that to resolve the dependencies,

_serviceCollection.AddSingleton<IService>(x =>      new Service(x.GetRequiredService<IOtherService>(), x.GetRequiredService<IAnotherOne>(), "")); 

The factory delegate is a delayed invocation. When ever the type is to be resolved it will pass the completed provider as the delegate parameter.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: