Asp.Net mvc - accessing IoC container from Session_Start
I want to manage my auth cookies similar to http://fishbowl.pastiche.org/2004/01/19/persistent_login_cookie_best_practice/
I'd like to check the cookie on session start, auth the user if there is one and exchange it for a new one on the start of each new session. I'd also like to create one if none exist.
This is to take care of the 'remember me' type functionality - similar to how SO works.
To do this I need to be able to pull services from the container from within the Session_Start method in the global.asax. While debugging the app I step through the Application_Start method where the container is constructed. Everything goes OK and the Container property of the global.asax is created. But when I step into the Session_Start - the Container is null.
Is there something happening that I'm not aware of? Is there a better way to be doing this?
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes开发者_如何学编程);
Container = new WindsorContainer().AddFacility<WcfFacility>()
.Install(Configuration.FromXmlFile("Configuration\\Windsor.config"))
.Install(FromAssembly.InDirectory(new AssemblyFilter(HttpRuntime.BinDirectory, "SonaTribe*.dll")));
}
/// <summary>
/// See http://fishbowl.pastiche.org/2004/01/19/persistent_login_cookie_best_practice/
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Session_Start(object sender, EventArgs e)
{
if (Container != null)
{
var accountService = Container.Resolve<IAccountService>();
var logger = Container.Resolve<ILogger>();
var forms = Container.Resolve<IFormsAuthentication>();
// if there is a cookie
if (Context.Request.Cookies["user-id"] != null)
{
try
{
//get the new cookie key from the server
var newUserSessionResponse = accountService.RegisterNewUserSession(new RegisterNewUserSessionRequest
{
SessionId = Context.Request.Cookies["user-id"].Value
});
if (newUserSessionResponse.Success)
{
//do something
}
else
{
logger.Info("Failed attaching the user to the session", newUserSessionResponse.Message);
}
}
catch (Exception exc)
{
logger.Error("Failed attaching the user to the session", exc);
}
}
else
{
//new user:
//do things
}
}
}
Thanks
w://
When implementing IContainerAccessor it's standard practice to store the container as a static variable of the global HttpApplication. See http://hammett.castleproject.org/?p=233 for reference.
If you don't use a static variable, the container will be lost when the ASP.NET runtime disposes the HttpApplication (the runtime internally maintains a pool of HttpApplication instances).
Move (the declaration of) Container into a static class and make sure it (Container) is static.
精彩评论