像下面的代码一样,我必须使用工厂/函数注册容器的方式,因为我提前不知道“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”,因为链接框架不会自动处理服务。
问题:
要让框架自动处理服务,有什么出路吗?
容器。AddSingleton <Func<string, IDBCache>> (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>()));