t4mvc:无法继承没有默认构造函数的控制器类? [英] t4mvc : Cannot inherit a controller class which has no default constructor?
问题描述
我在 MVC2 中使用 T4MVC.
I am using T4MVC with MVC2.
我有以下构建块:
一个简单的实体接口,它定义了每个 POCO 实体必须有一个
long Id
属性:
public interface IEntity
{
public long Id;
}
一个简单的 POCO 类,它实现了 IEntity
接口并具有一些字符串属性:
A simple POCO class which implements the IEntity
interface and has some string properties:
public class CD : IEntity
{
public long Id { get; set; }
public long Name { get; set; }
}
基本控制器:
A base controller:
public abstract class EntityController<T> : Controller where T : class, global::IEntity
{
public EntityController(IEntityManager<T> manager);
}
我在我的 CDController
中使用了这个基本控制器(其中 CDManager
实现了 IEntityManager
接口,这是一个要添加的 UnitOfWork 模式CRUD 功能):
I use this base controller in my CDController
(where CDManager
implements the IEntityManager
interface, which is a UnitOfWork pattern to add CRUD functionality):
public partial class CDController : EntityController<CD>
{
public CDController() : base(new CDManager()) { }
}
当我运行我的 t4 模板时,会生成以下代码:
When I run my t4 template, this code is generated:
namespace MyApp.Web.Controllers {
public partial class CDController {
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
protected CDController(Dummy d) { }
但这在编译过程中给了我一个错误:
But this gives me an error during compilation:
MyApp.EntityController
MyApp.EntityController<CD> does not contain a constructor that takes 0 arguments
我该如何解决这个问题?
How can I solve this?
推荐答案
我希望控制器基类是抽象的,并且它的构造函数受保护和参数化.通过向引发 NotImplementedException 的 ControllerBase 添加一个空白构造函数来解决这个问题.
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.
代码:
public abstract class ControllerBase : Controller
{
protected object AlwaysSupply { get; private set; }
public ControllerBase()
{
throw new NotImplementedException();
}
public ControllerBase(object alwaysSupply)
{
AlwaysSupply = alwaysSupply;
}
}
这将导致 T4MVC 生成可编译的代码.错误似乎是它总是试图为控制器类生成一个空白(无参数)构造函数.
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.
这篇关于t4mvc:无法继承没有默认构造函数的控制器类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!