Skip to content

Instantly share code, notes, and snippets.

@Deathspike
Last active June 14, 2018 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Deathspike/9a578e59e62c09893808 to your computer and use it in GitHub Desktop.
Save Deathspike/9a578e59e62c09893808 to your computer and use it in GitHub Desktop.
ASP.NET MVC Using a Context in a DataController
public abstract class DataController : Controller
{
private IContext _context;
#region Constructor
protected DataController()
{
_context = new Context();
}
#endregion
#region Contract
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(_context != null);
}
#endregion
#region Properties
public IContext Context
{
get { return _context; }
protected set { _context = value ?? _context; }
}
#endregion
#region Overrides of Controller
protected override void Dispose(bool disposing)
{
if (disposing)
{
Context.Dispose();
}
base.Dispose(disposing);
}
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext != null && filterContext.Controller != null)
{
filterContext.Controller.ViewBag.Context = Context;
}
base.OnActionExecuted(filterContext);
}
#endregion
}
public class MachineController : DataController
{
[HttpGet]
public ActionResult Index(int id = 0)
{
var machine = id == 0 ? null : Context.Machines.FirstOrDefault(x => x.Id == id);
return new ContentResult { Content = machine == null ? "No machine :-(" : machine.Name };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment