如何使AutoFac对每个顶级对象使用相同的嵌套依赖实例? (每个集线器的SignalRdependency injection)

我试图以这种测试通过的方式设置我的AutoFac注册:

[Test] public void Autofac_registration_test() { // Given var builder = new ContainerBuilder(); RegisterServices(builder); var container = builder.Build(); // When var firstHub = container.Resolve(); var secondHub = container.Resolve(); // Then firstHub.Should().NotBe(secondHub); firstHub.FooRepo.Context.Should().Be(firstHub.BarRepo.Context); firstHub.FooRepo.Context.Should().NotBe(secondHub.FooRepo.Context); } 

即我想在单个Hub一直使用相同的Context对象,但在创建新Hub时使用不同的Context对象。

RegisterServices目前只是:

 private void RegisterServices(ContainerBuilder builder) { builder.RegisterType(); builder.RegisterType(); builder.RegisterType(); builder.RegisterType(); // How should I scope this? } 

哪个在firstHub.FooRepo.Context.Should().Be(firstHub.BarRepo.Context);失败了firstHub.FooRepo.Context.Should().Be(firstHub.BarRepo.Context); 因为Context是临时范围的。

但是每个生命周期的范围上下文也会失败,这次是在firstHub.FooRepo.Context.Should().NotBe(secondHub.FooRepo.Context);

感觉这是一件合理的事情,所以我在这里错过任何明显的开箱即用的东西吗? 或者我是否必须手动操作来跟踪Hub创建?

(对于上下文,这是针对SignalR应用程序。根据SignalR请求创建集线器,因此这是尝试在正常webby情况下匹配HTTP请求的工作单元生存期)。

@Steven在评论中说的是正确的,我需要一种每个对象图的生活方式。

Castle.Windsor支持这个,所以我开始使用它来进行dependency injection而不是AutoFac。 注册现在看起来像:

 container.Register(Component.For().LifestyleTransient()); container.Register(Component.For().LifestyleTransient()); container.Register(Component.For().LifestyleTransient()); container.Register(Component.For().LifestyleBoundTo()); // Important bit 

有关更多信息,请参阅: http : //docs.castleproject.org/Windsor.LifeStyles.ashx?HL=scope#Bound_8