【发布时间】:2022-01-01 14:54:21
【问题描述】:
像下面的代码一样,我必须使用工厂/函数注册容器的方式,因为我不知道“userId”属性的值提前但只在运行时。这是有效的,功能方面没有问题。
container.AddSingleton<IBLogic, BLogic>(); //explicitly registration 'BLogic' service object
container.AddSingleton<Func<string, IDBCache>>
(p=> (userId) => new IDBCache(userId, p.GetService<IBLogic>()));
由于这里我使用的是“new IDBCache”,根据link 框架不会自动处理服务。
问题:
-
要让框架自动处理服务,有什么办法吗?
-
container.AddSingleton
> (p=> (userId) => new IDBCache(userId, p.GetService()));
由于我只是注册 func/factory 的定义而不是服务对象(如“BLogic”),AddSingleton 是否比使用下面的“AddScoped”或“AddTransisent”有任何优势?
container.AddTransisent<Func<string, IDBCache>>
(p=> (userId) => new IDBCache(userId, p.GetService<IBLogic>()));
【问题讨论】:
标签: c# dependency-injection asp.net-core-webapi asp.net-core-3.1 servicecollection