Sending from an ASP.NET MVC Controller

Component: NServiceBus
NuGet Package NServiceBus (6.x)

The sample demonstrates how to inject an endpoint instance info MVC controllers using Autofac's MVC integration.

Wire up Autofac

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

var endpointConfiguration = new EndpointConfiguration("Samples.MvcInjection.WebApplication");

endpointConfiguration.UsePersistence<LearningPersistence>();
endpointConfiguration.UseTransport<LearningTransport>();

endpoint = Endpoint.Start(endpointConfiguration).GetAwaiter().GetResult();

var mvcContainerBuilder = new ContainerBuilder();
mvcContainerBuilder.RegisterInstance(endpoint);

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

var mvcContainer = mvcContainerBuilder.Build();

DependencyResolver.SetResolver(new AutofacDependencyResolver(mvcContainer));

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

Injection into the Controller

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

public class DefaultController :
    Controller
{
    IEndpointInstance endpoint;

    public DefaultController(IEndpointInstance endpoint)
    {
        this.endpoint = endpoint;
    }

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

    [AllowAnonymous]
    public async Task<ActionResult> Send()
    {
        await endpoint.Send("Samples.Mvc.Endpoint", new MyMessage())
            .ConfigureAwait(false);
        return RedirectToAction("Index", "Default");
    }
}

Related Articles


Last modified