c# - 如何使用 .net 核心依赖注入(inject)指定参数?

标签 c# dependency-injection .net-core autofac

使用 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/

相关文章:

c# - 如何使用 WCF 传递我自己的类?

c# - Asp.NET WebApi 中类文件名称的路由

c# - 如何为属性创建自己的数据类型

c# - Ninject.ActivationException : Error activating IMainLicense 错误

c# - 简单注入(inject)器注入(inject) IEnumerable<Func<T>>

.net-core - 从 .net-core 中的代码覆盖率中排除类或方法

c# - 如何使用 C# 以编程方式编辑 Power BI Desktop 文档参数或数据源?

dependency-injection - 当有两个不同的构造函数时如何使用 Guice 进行注入(inject)?

.net-core - dotnet 发布 "Unable to load the service index for source https://api.nuget.org/v3/index.json"

c# - 如何将文件作为链接添加到 .NET Core 库中?