PreApplicationStartMethod属性导致异常

Joo*_*oop 4 c# asp.net .net-4.0

使用PreApplicationStartMethod属性发生了奇怪的事情.我确实在我的最新项目中实现了它.在AssemblyInfo.cs中,我有以下行:

[assembly: PreApplicationStartMethod(typeof(MyAssembly.Initializer), "Initialize")]
Run Code Online (Sandbox Code Playgroud)

Type和方法如下所示:

namespace MyAssembly
{
    public static class Initializer
    {
       public static void Initialize()
       {
           TranslationKeys.Initialize();
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我重建我的应用程序并在浏览器中加载它时,我收到以下错误:

程序集"MyWebApp,Version = 0.0.1.0,Culture = neutral,PublicKeyToken = null"上的PreApplicationStartMethodAttribute指定的方法无法解析.键入:'MyAssembly.Initializer',MethodName:'Initialize'.验证类型是否为public且方法是public和static(在Visual Basic中为Shared).

我真的不知道问题是什么.

Dav*_*bbo 10

奇怪的是,我们在ASP.NET团队中使用了很多这个功能,并没有碰到这个.为了帮助调试这个,您可以尝试运行以下代码,它执行类似于ASP.NET查找方法的操作吗?

运行它的最佳方法是创建一个控制台应用程序并将该代码放在那里.然后只需调用它,将它传递给您看到问题的程序集.然后,您将需要对其进行调试并仔细跟踪以查看发生了什么.

顺便说一下,在执行此操作之前,请仔细检查您是否将属性放在包含该类的同一程序集上.即它不能指向不同组件中的类型.

以下是尝试的代码:

using System;
using System.Web;
using System.Reflection;

public class TestClass {
    public static void TestPreStartInitMethodLocation(Assembly assembly) {
        var attributes = (PreApplicationStartMethodAttribute[])assembly.GetCustomAttributes(typeof(PreApplicationStartMethodAttribute), inherit: true);

        if (attributes != null && attributes.Length != 0) {
            PreApplicationStartMethodAttribute attribute = attributes[0];

            MethodInfo method = null;
            // They must be in the same assembly!
            if (attribute.Type != null && !String.IsNullOrEmpty(attribute.MethodName) && attribute.Type.Assembly == assembly) {
                method = FindPreStartInitMethod(attribute.Type, attribute.MethodName);
            }

            if (method == null) {
                throw new HttpException("Couldn't find attribute");
            }
        }
    }

    public static MethodInfo FindPreStartInitMethod(Type type, string methodName) {
        MethodInfo method = null;
        if (type.IsPublic) {
            method = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
                            binder: null,
                            types: Type.EmptyTypes,
                            modifiers: null);
        }
        return method;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一下,在执行此操作之前,请仔细检查您是否将属性放在包含该类的同一程序集上.即它不能指向不同组件中的类型. - - - - - - - - - - - - - - - - - - - - 谢谢!这就是诀窍.在我的解决方案中我有不同的项目.Initialize类与我的Web应用程序的解决方案不同. (2认同)