1

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?

Arnold Zahrneinder
  • 4,788
  • 10
  • 40
  • 76
  • Just as addition please read [Dependency Injection in Attributes: don’t do it!](https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=98) blog post. – kayess Feb 02 '16 at 15:20
  • @kayess: I'm not using injection in my Attribute, I'm getting the bind object out of the Kernel. Ninject should never cause an attribute to be triggered twice but it does. It has something to do with Ninject not the approach. – Arnold Zahrneinder Feb 02 '16 at 15:25
  • 1
    Did you take a read of this: https://github.com/ninject/Ninject.Web.Mvc/wiki/Dependency-injection-for-filters ? – spender Feb 02 '16 at 15:31
  • @spender: That article is really interesting, Thank you very much indeed. – Arnold Zahrneinder Feb 02 '16 at 15:42
  • Using a service locator for this dependency is a bad idea and there [is a proper way](http://stackoverflow.com/questions/32235660/unity-inject-dependencies-into-mvc-filter-class-with-parameters/32254851#32254851) to deal with injecting dependencies into authorization filters. If you use Attributes for meta-data and filters to control the behavior, you won't run into issues such as this one and won't have to resort to hacks to make DI work with Attributes. – NightOwl888 Feb 02 '16 at 16:18
  • @NightOwl888: That is Unity not Ninject. I've used both but I think Ninject has a better performance. – Arnold Zahrneinder Feb 02 '16 at 16:23
  • @Arrrr - That is the only reason why I didn't mark this question as an exact duplicate. The concept still applies regardless of which DI container (if any) you are using. You should use a globally registered filter that is injected with your dependencies rather than a service locator. – NightOwl888 Feb 02 '16 at 16:25
  • @NightOwl888: There is no doubt that what you are saying is correct as I myself have the same idea. The cause behind using this approach is laziness. – Arnold Zahrneinder Feb 02 '16 at 16:29

0 Answers0