Using ninject manually in MVC5 for View access

210 views Asked by At

I have the MVC5 ninject NuGet module installed on my web application, and I am injecting dependencies into controllers like a pro. It was incredibly easy to set up and use. One of my injected abstractions is the IApplicationSettingsProvider:

public interface IApplicationSettingsProvider
{
    string this[string key]
    {
        get;
    }
}

This is great, because my client has an old, poorly implemented "Application Settings Database" that they try to use to manage app settings across their suite of custom software. It's a mess, so I decided I wasn't going to depend on it.

Now, being able to access my application settings from any controller is great, but sometimes I need to access settings from a View. I decided I would make a static utility class that contained some of my injected class instances (including IApplicationSettingsProvider), but I couldn't figure out how to get access to the ninject kernel from NinjectWebCommon.cs! Without access to my bindings, I have no idea how to instantiate the utility class.

public class DependencyUtility {
    private DependencyUtility instance;

    public IApplicationSettingsProvider ApplicationSettingsProvider { get; set; }
    public IAuthenticationProvider AuthenticationProvider { get; set; }
    ...

    private DependencyUtility() {
        ApplicationSettingsProvider = ... ? ninject.Get<IApplicationSettingsProvider> ?
        AuthenticationProvider = ... ? ninject.Get<IAuthenticationProvider > ?
        ...
    }

    public static DependencyUtility GetInstance() {
        if(instance == null) {
            instance = new DependencyUtility();
        }

        return instance;
    }
}

Am I going about this the wrong way? I thought that a View should be able to access things like application settings directly, instead of packing relevant settings into models and viewbags (which would then have to be passed on to partials). What better way to access app settings than through an abstract, injected interface?

Does anyone know how to perform manual injections with the ninject kernel in MVC5? Or is there a better solution for delivering application settings to any view/partial?

0

There are 0 answers