Even before you start reading this post, I am sure many of you ll would have already had discussions on this like

“Why would you need to access services on your view?”

or

“Why would you want to inject dependencies into your view?”

and even

“Shouldn’t your View be plain and dumb and be used only to render HTML from a model?”

But anyways here is something that should help you, should you want to inject dependencies in your views.

For example’s sake let’s consider you have a ‘PermissionService’ which has a method IsModuleAllowedForUser(Guid userId, string moduleName) which decides if the module is allowed for the user and only then renders it. Now I want to access this service method from my view.

Demo.Services.Core.PermissionService.cs

namespace Demo.Service.Core
{
    public class PermissionService : IPermissionService
    {
        public bool IsModuleAllowedForUser(Guid userId, string moduleName)
        {
            // blah
        }
    }
}

Here’s a way to do it.

To start with we’ll need to create a class which will inherit from the WebViewPage class. I have injected the IPermissionService using property inject with Ninject.

Demo.Web.Core.MyInjectedWebViewPage.cs

using System.Web.Mvc;
using Ninject;

namespace Demo.Web.Core
{
    public abstract class MyInjectedWebViewPage : WebViewPage
    {
        [Inject]
        public IPermissionService PermissionManager { get; set; }
    }
}

in my NinjectWebCommon.cs class I have added bindings for the same

Bind<WebViewPage>().To<MaxInjectedWebViewPage<dynamic>>();
Bind<IPermissionService>().To<PermissionService>();    

and now in the view I can use the services like as shown below

@inherits MyInjectedWebViewPage

@if(PermissionManager.IsModuleAllowedForUser(Helper.GetUserId(), "precious"))
{
    <div>My precious div!</div>
}

Hope this helps :)

References:

  1. ASP.NET MVC 3 Service Location, Part 3: View Engines/View Pages
  2. Can you inject dependencies into a constructor of a custom WebViewPage, using an IOC container?