Asp.net mvc - how to provide a supertype controller level

I would like to use a class that extends Controlleras the default base type for controllers in my project, as opposed to using it myself Controller. So, I would do this:

public class FooController : MyBaseController

Is there a way I can provide this so that people cannot create controllers that extend Controllerdirectly?

+5
source share
5 answers

However, I prefer the unit testing approach above , here is another option using a custom factory controller.

public class MyControllerFactory<T> : DefaultControllerFactory where T : Controller
{
    #region Overrides of DefaultControllerFactory

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        if (!typeof(T).IsAssignableFrom(controllerType))
        {
            throw new NotSupportedException();
        }

        return base.GetControllerInstance(requestContext, controllerType);
    }

    #endregion
}

Global.asax :

ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory<MyBaseController>());

, , , MyBaseController, .

+3

unit test, ( ) , Controller, , MyBaseController.

[TestMethod]
public class All_Controllers_Derive_From_MyBaseController()
{
    // Act
    var controllerTypes = AppDomain.CurrentDomain
                                   .GetAssemblies()
                                   .SelectMany(asm => asm.GetTypes())
                                   .Where(t => t.IsSubclassOf(typeof(Controller))
                                   .ToList();

   // Verify
   foreach (var type in controllerTypes)
   {
        // Make sure the type isn't the actual controller type
        if (type is Controller)
            continue;

        Assert.IsTrue(type.IsSubclassOf(typeof(MyBaseController)), 
                           string.Format("{0} is not a subclass of the MyBaseController class", type.FullName));
   }
}

, - , , - , .

, , , .

+6

, : ( ) , , - "" , . System.Web.Mvc.Controller, . , , .

0

All Articles