如何使用 .net 核心依赖注入指定参数?
How to specify parameters using .net core dependency injection?
使用 Autofac 考虑此代码:
Builder.RegisterType<SecurityCache>().As<ISecurityCache>()
.WithParameter("id", AppId).SingleInstance()
SecurityCache
有3个参数,其中两个由DI容器处理,然后"id"参数使用WithParameter
指定。我如何使用 .NET Core DI 而不使用 Autofac 来做到这一点?
我想做
services.AddSingleton<ISecurityCache, SecurityCache>();
但我不确定如何指定 id
参数。
您可以在添加服务时使用实现工厂委托。
services.AddSingleton<ISecurityCache>(sp =>
new SecurityCache(AppId, sp.GetService<IService1>(), sp.GetService<IService2>())
);
或
services.AddSingleton<ISecurityCache>(sp =>
ActivatorUtilities.CreateInstance<SecurityCache>(sp, AppId)
);
委托提供对服务提供者的访问,因此您可以解决其他依赖关系。
来自评论
In this solution, is AppId
scoped and evaluated when .AddSingleton
is called?
AppId
在这种情况下,在调用工厂委托时被评估为常量。它似乎是注册该服务的函数的本地。
使用 Autofac 考虑此代码:
Builder.RegisterType<SecurityCache>().As<ISecurityCache>()
.WithParameter("id", AppId).SingleInstance()
SecurityCache
有3个参数,其中两个由DI容器处理,然后"id"参数使用WithParameter
指定。我如何使用 .NET Core DI 而不使用 Autofac 来做到这一点?
我想做
services.AddSingleton<ISecurityCache, SecurityCache>();
但我不确定如何指定 id
参数。
您可以在添加服务时使用实现工厂委托。
services.AddSingleton<ISecurityCache>(sp =>
new SecurityCache(AppId, sp.GetService<IService1>(), sp.GetService<IService2>())
);
或
services.AddSingleton<ISecurityCache>(sp =>
ActivatorUtilities.CreateInstance<SecurityCache>(sp, AppId)
);
委托提供对服务提供者的访问,因此您可以解决其他依赖关系。
来自评论
In this solution, is
AppId
scoped and evaluated when.AddSingleton
is called?
AppId
在这种情况下,在调用工厂委托时被评估为常量。它似乎是注册该服务的函数的本地。