I always use Ninject MVC to bind my actual Db to the DbContext
on run time for some reasons. One problem I have faced when using Ninject is that, when I need to access the bind object in an attribute such as the AuthorizeAttribute
, Ninject causes the attribute's functions to be triggered twice resulting in errors such as encountering null reference. For example:
public class UserAccessAttribute : AuthorizeAttribute
{
Boolean isLoggedIn = false;
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
DbContext db = App_Start.NinjectWebCommon.GetKernel.Get<DbContext>();
IdentityContext identityContext = new IdentityContext(httpContext);
....
return isLoggedIn;
}
...
}
In the above code, the Ninject cause the attribute to be triggered twice resulting in encountering a Null HttpContext
in the second trigger. I checked the code thoroughly for many times and I'm sure it has something to do with Ninject. So why does it happen, how to fix it?