依赖注入自定义ViewPage会产生奇怪的错误

时间:2009-11-20 09:49:11

标签: asp.net-mvc dependency-injection autofac

我正在尝试将内容注入自定义ViewPage(ModelViewPage,来自MvcContrib)

public class ValidatedModelViewPage<T> : ModelViewPage<T> where T : class
{
    public ValidatedModelViewPage(IEnumerable<IBehavior<IMemberElement>> elementBehaviors)
       : base(elementBehaviors.ToArray()) { }
}

我的Autofac注册如下:

builder.RegisterCollection<IBehavior<IMemberElement>>().As<IEnumerable<IBehavior<IMemberElement>>>();
builder.Register<NotNullBehavior>().MemberOf<IEnumerable<IBehavior<IMemberElement>>>();
builder.Register<StringLenghBehavior>().MemberOf<IEnumerable<IBehavior<IMemberElement>>>();

builder.RegisterGeneric(typeof(ValidatedModelViewPage<>));

但是当我尝试访问视图时出现此错误:

Compiler Error Message: CS1729: 'UKFS.Web.Views.ValidatedModelViewPage<UKFS.Data.Entities.Skadeanmälan>' does not contain a constructor that takes '0' arguments

Source Error:

Line 194:        private static object @__fileDependencies;
Line 195:        
Line 196:        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
Line 197:        public views_skadeanmälan_edit_aspx() {
Line 198:            string[] dependencies;


Source File: c:\Users\Carl\AppData\Local\Temp\Temporary ASP.NET Files\root\be9ddc15\a84d5058\App_Web_edit.aspx.b2d4184a.thgwih90.0.cs    Line: 196 

我很无能,但后来我看了App_Web_edit.aspx.b2d4184a.thgwih90.0.cs并发现了这个:

Line 190:      public class views_skadeanmälan_edit_aspx : UKFS.Web.Views.ValidatedModelViewPage<Skadeanmälan>, System.Web.SessionState.IRequiresSessionState, System.Web.IHttpHandler {
Line 191:          
Line 192:          private static bool @__initialized;
Line 193:          
Line 194:          private static object @__fileDependencies;
Line 195:          
Line 196:          [System.Diagnostics.DebuggerNonUserCodeAttribute()]
Line 197:          public views_skadeanmälan_edit_aspx() {

当然,生成的类views_skadeanmälan_edit_aspx继承自我的UKFS.Web.Views.ValidatedModelViewPage,当它尝试使用默认构造实例时..你能解决它吗?

1 个答案:

答案 0 :(得分:1)

您将无法将构造函数注入ViewPages,因为aspx编译器生成一个空的ctor,并且它从您的基类派生,您的基类也必须有一个空的ctor。

我会寻找属性注入,否则尝试完成以下操作:

  • 找到实例化视图页面的地方,并在那里获取Autofact以实例化页面
  • 让aspx编译器不生成空ctor

我不知道如何做这些事情,所以我的目标是注入财产