Skip to content

Instantly share code, notes, and snippets.

@steida
Created September 10, 2010 22:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steida/574505 to your computer and use it in GitHub Desktop.
Save steida/574505 to your computer and use it in GitHub Desktop.
using System;
using System.Configuration;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.WebPages.Compilation;
using MyApp.Fixtures;
using MyApp.Models;
using MyApp.Services;
namespace MyApp
{
public class Db : DbContext
{
public DbSet<Role> Roles { get; set; }
public DbSet<User> Users { get; set; }
}
public class App : System.Web.HttpApplication
{
const string SessionKey = "Db.Session";
public static Db Db
{
get
{
return (Db)HttpContext.Current.Items[SessionKey];
}
}
public App()
{
BeginRequest += MvcApplication_BeginRequest;
AuthenticateRequest += MvcApplication_AuthenticateRequest;
EndRequest += MvcApplication_EndRequest;
}
void MvcApplication_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Items[SessionKey] = new Db();
}
void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Request.Path.Contains("assets/"))
return;
AccountService.AuthenticateRequest();
}
void MvcApplication_EndRequest(object sender, EventArgs e)
{
var disposable = HttpContext.Current.Items[SessionKey] as IDisposable;
if (disposable != null)
disposable.Dispose();
}
protected void Application_Start()
{
Database.SetInitializer<Db>(new DbInitializer());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
// turn off the unnecessary file exists check
routes.RouteExistingFiles = true;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("assets/{*pathInfo}");
routes.IgnoreRoute("favicon.ico");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "MyApp.Controllers" }
);
}
}
}
@steida
Copy link
Author

steida commented Sep 11, 2010

Example: var user = App.Db.Users.Find(id);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment