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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With