Skip to content

Instantly share code, notes, and snippets.

@mhinze
Created November 19, 2013 19:43

Revisions

  1. mhinze created this gist Nov 19, 2013.
    65 changes: 65 additions & 0 deletions BaseController.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,65 @@
    using System.Threading.Tasks;
    using System.Web.Mvc;
    using JetBrains.Annotations;
    using ShortBus;

    public abstract class BaseController : Controller
    {
    public IMediator Mediator { get; set; }

    protected Response<TResult> Query<TResult>(IQuery<TResult> query)
    {
    return Mediator.Request(query);
    }

    protected async Task<Response<T>> QueryAsync<T>(IQuery<T> query)
    {
    return await Mediator.RequestAsync(query);
    }

    protected void Command<T>(T command)
    {
    var result = Mediator.Send(command);
    if (result.HasException())
    {
    throw result.Exception;
    }
    }

    protected async Task CommandAsync<T>(T command)
    {
    var result = await Mediator.SendAsync(command);
    if (result.HasException())
    {
    throw result.Exception;
    }
    }

    [AspMvcView]
    protected ViewResult View<TData>(Response<TData> model)
    {
    return View(string.Empty, model);
    }

    protected ViewResult View<TData>([AspMvcView] string viewName, Response<TData> model)
    {
    if (model.HasException())
    return base.View("~/Views/Shared/Error.cshtml", model);

    return View(viewName, model.Data);
    }

    [AspMvcPartialView]
    protected PartialViewResult PartialView<TData>(Response<TData> model)
    {
    return PartialView(string.Empty, model);
    }

    protected PartialViewResult PartialView<TData>([AspMvcPartialView] string viewName, Response<TData> model)
    {
    if (model.HasException())
    return base.PartialView("~/Views/Shared/ErrorPartial.cshtml", model);

    return PartialView(viewName, model.Data);
    }
    }