使用 Autofac 考虑这段代码:
Builder.RegisterType<SecurityCache>().As<ISecurityCache>()
.WithParameter("id", AppId).SingleInstance()
SecurityCache
有3个参数,其中两个由DI容器处理,然后使用WithParameter
指定“id”参数。我如何使用 .NET Core DI 执行此操作,而不是使用 Autofac?
我想做
services.AddSingleton<ISecurityCache, SecurityCache>();
但我不确定如何指定 id
参数。
最佳答案
您可以在添加服务时使用实现工厂委托(delegate)。
services.AddSingleton<ISecurityCache>(sp =>
new SecurityCache(AppId, sp.GetService<IService1>(), sp.GetService<IService2>())
);
或
services.AddSingleton<ISecurityCache>(sp =>
ActivatorUtilities.CreateInstance<SecurityCache>(sp, AppId)
);
委托(delegate)提供对服务提供者的访问,因此您可以解决其他依赖关系。
来自评论
In this solution, is
AppId
scoped and evaluated when.AddSingleton
is called?
AppId
在这种情况下在调用工厂委托(delegate)时被评估为常量。它似乎在注册服务的函数本地。
关于c# - 如何使用 .net 核心依赖注入(inject)指定参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51307079/