Inject a dependency into a custom model binder and using InRequestScope using Ninject

The ModelBinders are reused by MVC for multiple requests. This means they have a longer lifecycle than request scope and therefore aren’t allowed to depend on objects with the shorter request scope life cycle. Use a Factory instead to create the IPostRepository for every execution of BindModel

How do I handle classes with static methods with Ninject?

If you’re building a singleton or something of that nature and trying to inject dependencies, typically you instead write your code as a normal class, without trying to put in lots of (probably incorrect) code managing the singleton and instead register the object InSingletonScope (v2 – you didnt mention your Ninject version). Each time you … Read more

Ninject Binding Attribute to Filter with Constructor Arguments

I have figured it out (thanks to Remo’s directions and documentation). Use the appropriate .WithConstructorArgument extension whether you are binding to a Controller or Action filter. For example binding my action filter looks like this: kernel.BindFilter<AuthorizationFilter>(FilterScope.Action, 0) .WhenActionMethodHas<RequireRolesAttribute>() .WithConstructorArgumentFromActionAttribute<RequireRolesAttribute>(“requiredRoles”, o => o.RequiredRoles); Once I understood the Func<> signature, it all became clear. The best way … Read more

How to inject UserManager & SignInManager

Prerequisites Start a new MVC5 application using the MVC template. This will install all the necessary dependencies as well as deploy the Startup.Auth.cs file which contains the bootstrap code for Microsoft.AspNet.Identity (it als includes the all the references for Microsoft.AspNet.Identity). Install the following packages and update them to the latest afterwards. Install-Package Ninject Install-Package Ninject.MVC5 … Read more

Using HttpContext.Current in WebApi is dangerous because of async

HttpContext.Current gets the current context by Thread (I looked into the implementation directly). It would be more correct to say that HttpContext is applied to a thread; or a thread “enters” the HttpContext. Using HttpContext.Current inside of async Task is not possible, because it can run on another Thread. Not at all; the default behavior … Read more