2016-02-26 52 views
0

我想知道是否有办法在注册后随时检索autofac容器。我注册模块如下(使用NSB 5.0):当我的端点开始我注册监听器(实施IWantToRunWhenBusStartsAndStops),其从一个WebSphereMQ检索消息在NServiceBus中检索Autofac IContainer

var builder = new ContainerBuilder(); 
builder.RegisterModule(new AutofacConfigModule()); 
container = builder.Build(); 
busConfiguration.UseContainer<AutofacBuilder>(c => c.ExistingLifetimeScope(container)); 

。为了处理这些消息,我定义了一个接口(类似于NServiceBus IHandleMessages <>),然后我想解析并将反序列化消息传递给进一步处理。为了解决我的自定义接口实现,我想使用我已经注册的容器NServiceBus,但我不知道如何做到这一点。有没有办法检索它?

回答

2

如果注册在容器中的接口解决您的依赖关系,就可以使用构造注射来解决它们。考虑这样的事情:

var cfg = new BusConfiguration(); 
var builder = new ContainerBuilder(); 
builder.RegisterInstance<IMyCustomHandler>(new MyCustomHandler()); 
var container = builder.Build(); 
cfg.UseContainer<AutofacBuilder>(c => c.ExistingLifetimeScope(container)); 

然后,你可以通过构造函数参数注入IMyCustomHandler,它应该自动NServiceBus解决。

这有帮助吗?

+0

我结束了一些类似于你的建议(注册一个组件并注入容器作为属性),尽管我认为你的解决方案更好。谢谢您的帮助! – 5earch

0

是否可以使用ContainerDefinition注册您自己的Autofac中间件实现?

​​

你可以注册Autofac和根ILifetimeScope存储为静态属性在应用程序中使用。

喜欢的东西:

public static class Container 
{ 
    public static ILifetimeScope LifetimeScope { get; set; } 
} 

public class MyContainer : ContainerDefinition 
{ 
    public override IContainer CreateContainer(ReadOnlySettings settings) 
    { 
     var builder = new ContainerBuilder(); 
     builder.RegisterModule(new AutofacConfigModule()); 
     Container.LifetimeScope = builder.Build(); 
     return Container.LifetimeScope; 
    } 
} 

然后使用

Container.LifetimeScope.Resolve<IHandleDeserializedMessages>(); 

(没有经过充分测试的代码示例)