Sending from an ASP.NET MVC Controller

Component: NServiceBus | Nuget: NServiceBus (Version: 6.x)

Wire up Autofac

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

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

endpointConfiguration.UseSerialization<JsonSerializer>();
endpointConfiguration.UsePersistence<InMemoryPersistence>();
endpointConfiguration.EnableInstallers();
endpointConfiguration.SendFailedMessagesTo("error");

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.

Edit
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