0

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?

mafian911
  • 91
  • 7
  • If a view needs access to settings, I would usually put them in the model. Don't forget - views should just be display templates with no code. – Kevin Kuszyk Nov 13 '14 at 17:23
  • I understand that views shouldn't contain business logic. In my scenario, I have a partial within a view that needs to know the host domain of an image asset server. Normally, these domains are hard coded into image source attributes, but this needed to be configurable. I didn't want to burden the model with something unrelated to the task at hand, and I need to know this across the site. I don't know if that justifies accessing application settings from a partial, but to me it makes perfect sense to do it that way. – mafian911 Nov 13 '14 at 18:16

0 Answers0