t4mvc : Cannot inherit a controller class which has no default constructor?

后端 未结 3 1316
独厮守ぢ
独厮守ぢ 2021-01-17 18:23

I am using T4MVC with MVC2.

I have the following building blocks:

  1. A simple entity interface which defines that every POCO entity must have a l

相关标签:
3条回答
  • 2021-01-17 18:56

    I see the problem, and it comes down to T4MVC not quite doing the right thing when dealing with generic classes. Normally it would generate a default ctor for it in a partial class, but the fact that it's generic is throwing it off.

    You should be able to work around simply by adding a default ctor yourself, e.g.

    public abstract partial class EntityController<T> : Controller where T : class, IEntity {
        public EntityController() { }
    
        // etc...
    }
    
    0 讨论(0)
  • 2021-01-17 19:04

    I've noticed something very odd:

    I've added the empty constructor to the base class, but without the throw new NotImplementedException(); and it works fine.

    But here's the odd thing, when calling the controller if I have an url like /{controller}?params (default action being set to Index in the RouteConfig) the parameterless private controller on the base class is called. But when I have an url like /{controller}/{action}?params then the constructor with parameters is called.

    0 讨论(0)
  • 2021-01-17 19:06

    I wanted by controller base class to be abstract and it's constructor protected and parametrized. Got around this issue by adding a blank constructor to ControllerBase that throws a NotImplementedException.

    Doesn't quite feel right but it gets the job done. Only issue is when combined with dependency injection the wrong constructor will be called - since it throws an exception the app will bum out.

    Code:

    public abstract class ControllerBase : Controller
    {
        protected object AlwaysSupply { get; private set; }
    
        public ControllerBase()
        {
            throw new NotImplementedException();
        }
    
        public ControllerBase(object alwaysSupply)
        {
            AlwaysSupply = alwaysSupply;
        }
    }
    

    This will cause T4MVC to generate compilable code. The fault seems to be it always tries to generate a blank (no parameters) constructor for controller classes.

    Hope this helps someone.

    0 讨论(0)
提交回复
热议问题