How can I hook ASP .NET compilation process?

时间:2017-03-14 23:02:26

标签: c# asp.net asp.net-mvc iis-7 iis-7.5

ASP .NET Dynamically generate classes & compiles an assembly to the Temporary ASP.NET files.

I would like to be able to get information when this process happens. Ultimately, I would like to have an event that will fire the name of the source file and the generated class name + assembly so I could map between methods in the original source file and methods in the generated classes.

I'll appreciate your help.

2 个答案:

答案 0 :(得分:1)

我建议使用FileSystemWatcher类为相应的目录创建一个观察程序,然后根据它进行处理。

您可以在此处找到有关它的信息: https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx

基本上,观察者将允许您在目录中获取事件以进行文件更改,然后您可以使用Assembly类来加载和处理有关生成的代码的反射信息。我不能说这很容易,但它是非常可行的。您还希望拥有一个数据库来跟踪已更改的内容,将源代码映射到已编译的代码等,以使其更加健壮。

希望这能指出你正确的方向。

答案 1 :(得分:1)

阐述@Inari的建议

只需确保您在 IncludeSubdirectories 设置为true的情况下观看文件夹 AppDomain.CurrentDomain.DynamicDirectory 。为了确保您不会太晚监视所有编辑,您需要首先启动,因此我建议您使用 PreApplicationStartMethodAttribute

这有助于在此过程发生时获取信息。 如果您还想查找源文件,这取决于您感兴趣的内容(仅编译的程序集?=>反射,还编译了razor pages =>名称)。

[assembly: PreApplicationStartMethod(typeof(Demo.CompilationWatcher), "Initialize")]
namespace Demo
{
    public static class CompilationWatcher
    {
        public static void Initialize()
            {
                while (true)
                {

                    FileSystemWatcher watcher = new FileSystemWatcher();
                    watcher.Path = AppDomain.CurrentDomain.DynamicDirectory;
                    watcher.IncludeSubdirectories = true;

                    watcher.NotifyFilter = NotifyFilters.Attributes |
                    NotifyFilters.CreationTime |
                    NotifyFilters.DirectoryName |
                    NotifyFilters.FileName |
                    NotifyFilters.LastAccess |
                    NotifyFilters.LastWrite |
                    NotifyFilters.Security |
                    NotifyFilters.Size;

                    watcher.Filter = "*.*"; // consider filtering only *.dll, *.compiled etc

                    watcher.Changed += new FileSystemEventHandler(OnChanged);
                    watcher.Created += new FileSystemEventHandler(OnChanged);

                    watcher.EnableRaisingEvents = true;
                }

            }

            public static void OnChanged(object source, FileSystemEventArgs e)
            {
                // your thread-safe logic here to log e.Name, e.FullPath, an d get the source file through reflection / name etc. ... 
            }

    }

}