The event model in System.Web.HttpApplication is part of ASP.NET, not MVC. It is not intended for use with dependency injection.
The answer proposed by Cyril uses the service locator to get a link to this service. This is far from ideal, since you depend on the service locator in your code.
An MVC-oriented way of implementing cross-cutting issues (for example, loading user data into session state) is to use globally registered filters. You can implement IAuthorizationFilter or IActionFilter to get the desired effect. In this case, it makes sense to use IActionFilter , since you want to wait until you are sure that there is an authorized user before calling him.
NOTE. . Although this answers your specific question, it is best not to use the session state for this scenario in MVC. An alternative is to use the ASP.NET ID with claims to store user profile data instead of using a session.
using System; using System.Web.Mvc; using System.Security.Principal; public class GetUserActionFilter : IActionFilter { private readonly IUserRepository userRepository; public GetUserActionFilter(IUserRepository userRepository) { if (userRepository == null) throw new ArgumentNullException("userRepository"); this.userRepository = userRepository; } public void OnActionExecuted(ActionExecutedContext filterContext) {
Now, to add your filter worldwide, you need to:
- Register the filter and its dependencies with Autofac.
- Pass the container to the static
RegisterGlobalFilters method.
Register a filter
Using a named instance to distinguish it from other potential IActionFilter instances.
builder.RegisterType<GetUserActionFilter>() .Named<IActionFilter>("getUserActionFilter");
Skip container
FilterConfig.cs
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters, IContainer container) { filters.Add(container.ResolveNamed<IActionFilter>("getUserActionFilter")); filters.Add(new HandleErrorAttribute()); } }
Global.asax.cs
public class MvcApplication : System.Web.HttpApplication {
ContainerConfig.cs
public class ContainerConfig { public static IContainer RegisterContainer() {
Please note that I just used the repository service here, since the HttpContext is already accessible through the action filter, and additional logic is needed here, because we donβt know exactly whether it exists in the session state or not, or not even the user to search, therefore our filter performs these checks in addition to loading session state.