Search code examples
azurenservicebusazure-mobile-services

Combine azure mobile service autofac with nservicebus registrations


I am trying to combine the registrations of the azure mobile service and the nservicebus registrations. When i try to inject the IBus into an controller it doesn't work.

public class AutofacConfig
{
      public static void Register(HttpConfiguration http, ContainerBuilder container)
      {
            var busConfiguration = new BusConfiguration();
            busConfiguration.UseContainer<AutofacBuilder>(c => c.ExistingLifetimeScope(container.Build()));

            var bus = Bus.Create(busConfiguration);
            bus.Start();
      }
}

I need to call container.Build() in order to pass the current container to NServiceBus. but this results in an error in ServiceConfig.Initialize in my WebApiConfig class

public static class WebApiConfig
    {
        public static void Register()
        {
            // Use this class to set configuration options for your mobile service
            ConfigOptions options = new ConfigOptions();

            // Use this class to set WebAPI configuration options
            HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options, AutofacConfig.Register));


            // To display errors in the browser during development, uncomment the following
            // line. Comment it out again when you deploy your service for production use.
            // config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            Database.SetInitializer(new nos_devInitializer());
        }
    }

Solution

  • Ok, i see i can resolve the ILifetimeScope from the dependencyresolver. Call this method after ServiceConfig.Initialize and the two registrations are paired.

    public class NServiceBusConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var resolver = (AutofacWebApiDependencyResolver)config.DependencyResolver;
            var scope = resolver.GetService<ILifetimeScope>();
    
            var busConfiguration = new BusConfiguration();
            busConfiguration.UseContainer<AutofacBuilder>(f => f.ExistingLifetimeScope(scope));
    
            var bus = Bus.Create(busConfiguration);
            bus.Start();
        }
    }