Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify parameters using .net core dependency injection?

Consider this code using Autofac:

 Builder.RegisterType<SecurityCache>().As<ISecurityCache>()
    .WithParameter("id", AppId).SingleInstance()

SecurityCache has 3 parameters, two of which are handled by the DI container, and then the "id" parameter is specified using WithParameter. How can I do this with .NET Core DI, not using Autofac?

I want to do

services.AddSingleton<ISecurityCache, SecurityCache>(); 

But I am unsure how to specify the id parameter.

like image 896
phelhe Avatar asked Jul 12 '18 13:07

phelhe


1 Answers

You can use the implementation factory delegate when adding your service.

services.AddSingleton<ISecurityCache>(sp =>
    new SecurityCache(AppId, sp.GetService<IService1>(), sp.GetService<IService2>())
); 

OR

services.AddSingleton<ISecurityCache>(sp =>
    ActivatorUtilities.CreateInstance<SecurityCache>(sp, AppId)
); 

The delegate provides access to the service provider so you can resolve the other dependencies.

From comments

In this solution, is AppId scoped and evaluated when .AddSingleton is called?

AppId in that case is evaluated as a constant when the factory delegate is invoked. It appears to be local to the function that registered the service.

like image 59
Nkosi Avatar answered Sep 22 '22 09:09

Nkosi