Question

I'm trying to bind IAuthenticationManager with Ninject so it can be injected into my AuthenticationService. The problem is that I currently get the IAuthenticationManager from HttpContext.GetOwinContext() on my Controller, like so:

private IAuthenticationManager AuthenticationManager {
    get {
        return this.HttpContext.GetOwinContext().Authentication;
    }
}

How do I go about creating the binding with Ninject so that it knows to look for IAuthenticationManager from the HttpContext.GetOwinContext() at runtime? Is it possible? Does my question even make sense? Thanks in advance!

Was it helpful?

Solution

So, I figured it out. Ninject provides access to the HttpContext directly, so I did this:

kernel.Bind<IAuthenticationManager>().ToMethod(
    c =>
        HttpContext.Current.GetOwinContext().Authentication).InRequestScope();

For anyone curious, here it is.

Update for @Meep

So, Ninject doesn't have to live in the same project as MVC. For that purpose I pulled it out into a separate project, in my case called "X.Dependencies". It references all other projects, NuGet packages, etc. that I need to actually set my bindings. It contains two files, the original C# file Ninject creates when added which I've renamed to NinjectConfiguration, and a cheaty file called AssemblyReferences which is required to make Visual Studio actually import all assemblies into the main project. Here's the code for it:

/// <summary>
/// Cheaty way to force Visual Studio to find all assembly references, even the ones not directly used by the main project.
/// </summary>
internal static class AssemblyReferences {
    internal static readonly Type t1 = typeof(Ninject.Web.Mvc.MvcModule);
}

Now, I suppose this could be avoided, but it's worked for me so far. I'm open to suggestions though. I just add a reference to it from my MVC project and let the WebActivator take care of initializing it, just as it had using the regular way.

I've also pulled out Owin into its' own project named "X.Owin" and it contains the usual Owin startup class, which I've simply renamed to OwinConfiguration.

Both of these are part of my "Domain Layer" which also contains a couple of other helper projects. One other noteworthy project from the list would be my "X.Mappings" which is for configuring AutoMapper mappings. It also uses the WebActivator to self initialize so I just add a reference to it in the MVC project.

Since I've pulled out a lot of code from the MVC project all it does at this point is basically routing and view rendering. Everything else is passed onto the helper projects as needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top