Service not injected into razor view

Aug 3, 2012 at 11:45 AM

Currently I am trying to access a service through one of my razor views. I followed the instructions in the documentation... And created a new base class for my views that has the service as a property.

public abstract class ViewWithServices<T> : WebViewPage<T>
	public CoreAuthorizer Authorizer { set; protected get; }

and in the razor view
@inherits MvcRunner.Views.ViewWithServices<object>

I also registered it in my runweb under SystemServices. The CoreAuthorizer is a visible property in the view but I get a null reference at run time when I try to accessany of the service actions.

Is there any additional step I am missing?




Aug 3, 2012 at 12:03 PM

We also confirmed that the following in NakedObjectsStart.cs does get hit.

		public static void PostStart ()
			RunWeb.Run ();
			DependencyResolver.SetResolver (new NakedObjectsDependencyResolver ());

Aug 3, 2012 at 12:57 PM

Razor views have a different base class to asp views and so the injector is ignoring them. We'll raise a ticket but for the moment an easy workaround is to create a new class in App_Start


// Copyright © Naked Objects Group Ltd ( 
// All Rights Reserved. This code released under the terms of the 
// Microsoft Public License (MS-PL) ( 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using NakedObjects.Architecture.Reflect;
using NakedObjects.Core.Context;

namespace NakedObjects.Web.Mvc {

    public class RazorNakedObjectsDependencyResolver : IDependencyResolver {

        private IContainerInjector injector;

        private IContainerInjector Injector {
            get {
                if (injector == null) {
                    var servicesToInject = NakedObjectsContext.ObjectPersistor.GetServices().Select(no => no.Object).ToArray();
                    injector = NakedObjectsContext.Reflector.CreateContainerInjector(servicesToInject);

                return injector;

        public object GetService(Type serviceType) {
            // ViewPage = aspx,  WebViewPage = razor
            if (typeof(IController).IsAssignableFrom(serviceType)
                || typeof(ViewPage).IsAssignableFrom(serviceType)
                || typeof(WebViewPage).IsAssignableFrom(serviceType)) {
                object obj = Activator.CreateInstance(serviceType);
                return obj;
            return null;

        public IEnumerable<object> GetServices(Type serviceType) {
            return new object[] {};

and use that to inject


  public static void PostStart() {
            DependencyResolver.SetResolver(new RazorNakedObjectsDependencyResolver());

Aug 3, 2012 at 1:29 PM

great. We'll try it soon.

Aug 3, 2012 at 2:09 PM

Great! Thanks I've tested it and it works great. :)