如何使用.net核心依赖项注入指定参数?

phe*_*lhe 3 c# dependency-injection autofac .net-core

使用Autofac考虑以下代码:

 Builder.RegisterType<SecurityCache>().As<ISecurityCache>()
    .WithParameter("id", AppId).SingleInstance()
Run Code Online (Sandbox Code Playgroud)

SecurityCache有3个参数,其中两个由DI容器处理,然后使用来指定“ id”参数WithParameter。如何使用.NET Core DI而不是使用Autofac做到这一点?

我想要做

services.AddSingleton<ISecurityCache, SecurityCache>(); 
Run Code Online (Sandbox Code Playgroud)

但是我不确定如何指定id参数。

Nko*_*osi 6

添加服务时,可以使用实现工厂委托。

services.AddSingleton<ISecurityCache>(sp =>
    new SecurityCache(AppId, sp.GetService<IService1>(), sp.GetService<IService2>())
); 
Run Code Online (Sandbox Code Playgroud)

委托提供对服务提供商的访问,因此您可以解决其他依赖关系。

  • 同意,这是您可以使用“开箱即用”Microsoft 容器做的最好的事情。Microsoft 容器是相当低的公分母,并且可能永远不会具有 Autofac、SimpleInjector 或其他更强大的容器的功能。 (2认同)