nservicebusstructuremappluggable

How can I get handle on NServiceBus child container inside the message handler?


I am using NServiceBus 4.0.3, StructureMap 2.6.4.0 and NHibernate

I have configured my endpoint as follows:

public class EndpointConfig : IConfigureThisEndpoint, 
    AsA_Client, IWantCustomInitialization
{
    public void Init()
    {
        Configure.With(
            .StructureMapBuilder(getContainer());

        Configure.Features.Disable<SecondLevelRetries>();
        Configure.Features.Disable<Sagas>();
        Configure.Features.Disable<TimeoutManager>();
    }
}

private IContainer getContainer()
{
    var container = new Container(x =>
    {

        x.Scan(s =>
        {
            s.WithDefaultConventions();
            s.TheCallingAssembly();
      });

        x.ForSingletonOf<ISessionFactory>().Use(createSessionFactory());
        x.For<ISession>().Use(context => 
            context.GetInstance<ISessionFactory>().OpenSession());
    });

    return container;
}

I have a pluginfamily and I want to get an instance of the object at runtime(cant use constructor injection).

In StructureMap world, it can be done by using:

ObjectFactory.GetNamedInstance<ISomething>("familyName");

But when I am using NServiceBus with structuremap, it gets a nested container for each message.
When I want to get an instance of an object, the above code will only give me an instance from the parent container. Since the ObjectFactory was never initialize, it doesn't get an instance.

Event if I initialize the ObjectFactory with my container, since it is a static wrapper it wont be safe to use it per message.

So how do I get handle on my child container for the given message so that I can use the plugin family?


Solution

  • You can't access the child through the NServiceBus IBuilder api (https://github.com/Particular/NServiceBus/issues/1565)

    But I'm pretty sure you can get at it by injecting the native IContainer interface provided by StructureMap into you handler.

    In short:

    Take a dependency on StructureMap.IContainer