如何为每个范围组织延迟的服务解决方案?

问题描述 投票:0回答:1

我有一个在应用程序启动时创建的单例对象。对象具有子服务的依赖关系,应该在已知作用域键之后在每个作用域中稍后创建子服务。如何注册这种依赖关系?

testContainer.Register<DelayedServiceConsumer>(Lifestyle.Singleton);
testContainer.Register<Func<IDelayedService>>(() => new DelayedService(), Lifestyle.Scoped);


public class DelayedServiceConsumer() {
   public DelayedServiceConsumer(Func<IDelayedService> delayedServiceFactory) {....} 

   public void SomeMethod() {
      // I need per scope resolution happening here. If we already have service for that scope container should just return that instance. Otherwise new instance should be created for the scope
      var service = delayedServiceFactory(); 
   }
}
simple-injector
1个回答
0
投票

将您的注册更改为:

testContainer.RegisterInstance<Func<IDelayedService>>(() => new DelayedService());

有关更多信息,请参见文档:https://simpleinjector.readthedocs.io/en/latest/howto.html#register-factory-delegates

© www.soinside.com 2019 - 2024. All rights reserved.