Sending from an ASP.NET MVC Controller

Component: NServiceBus
NuGet NServiceBus (5.x)

Wire up Autofac

Open Global.asax.cs and look at the ApplicationStart method.

var builder = new ContainerBuilder();

// Register the MVC controllers.
builder.RegisterControllers(typeof(MvcApplication).Assembly);

// Set the dependency resolver to be Autofac.
var container = builder.Build();

var busConfiguration = new BusConfiguration();
busConfiguration.EndpointName("Samples.MvcInjection.WebApplication");
// ExistingLifetimeScope() ensures that IBus is added to the container as well,
// allowing resolve IBus from the components.
busConfiguration.UseContainer<AutofacBuilder>(
    customizations: customizations =>
    {
        customizations.ExistingLifetimeScope(container);
    });
busConfiguration.UseSerialization<JsonSerializer>();
busConfiguration.UsePersistence<InMemoryPersistence>();
busConfiguration.EnableInstallers();

bus = Bus.CreateSendOnly(busConfiguration);

DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);

Injection into the Controller

The endpoint instance is injected into the DefaultController at construction time.

public class DefaultController :
    Controller
{
    IBus bus;

    public DefaultController(IBus bus)
    {
        this.bus = bus;
    }

    public ActionResult Index()
    {
        return View();
    }

    [AllowAnonymous]
    public ActionResult Send()
    {
        bus.Send("Samples.Mvc.Endpoint", new MyMessage());
        return RedirectToAction("Index", "Default");
    }
}

Related Articles


Last modified