如何组织每个范围的延迟服务解析?

时间:2020-02-12 12:47:18

标签: simple-injector

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

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(); 
   }
}

1 个答案:

答案 0 :(得分:0)

将您的注册更改为:

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

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