c# - 我们可以在 DotNet 类库项目中使用 global.asax 文件吗

标签 c# asp.net .net clr

我们可以在 .NET 类库项目中使用 Global.asax 文件吗?因为我在任何地方都没有看到 Global.asax 文件只能用于基于 Web 的应用程序。

Global.asax 文件的代码在应用程序启动时被.net 框架编译和调用。我想在我的类库中使用类似的功能,即当我的类库被加载到内存中时,类库的 Global.asax 文件的 Application_Start 将被调用.

我知道这可以使用静态构造函数来使用,但我想为此使用 Global.asax

任何建议/意见将不胜感激..

谢谢

最佳答案

global.asax 文件是 ASP.NET 应用程序的一项功能。它在 DLL(类库项目)中不可用。

没有标准的方法(使用 C#)在程序集加载时运行一些代码,即使 CLR 似乎有这样的功能。看看this question了解更多信息和想法。例如,一个答案提到了一种名为 InjectModuleInitializer 的工具,它作为构建后步骤运行,将模块初始化方法注入(inject) .NET 程序集。

这是 blog post introducing InjectModuleInitializer 的一小段摘录:

One feature of the CLR that is not available in C# or VB.NET are module initializers (or module constructors). A module initializer is simply a global function which is named .cctor and marked with the attributes SpecialName and RTSpecialName. It is run when a module (each .NET assembly is comprised of one or more modules, typically just one) is loaded for the first time, and is guaranteed to run before any other code in the module runs, before any type initializers, static constructors or any other initialization code.

关于c# - 我们可以在 DotNet 类库项目中使用 global.asax 文件吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31232271/

相关文章:

c# - 如果两个功能几乎相同,如何遵守 DRY 原则?

.net - 将对象设置为空

c# - 替换声明 block 为空的 CSS 规则集

c# - 6 位小数和 1-4 位以上的正则表达式

c# - 关于 C# 中的字符串和引用的可能愚蠢的问题

c# - 从另一个页面的代码隐藏中获取 ASP.Net 页面的 URL

.net 4 中的 ASP.NET Web 服务应用程序

c# - 如何将流读取器响应转换为类对象?

.net - 将 DBML 导出为 SQL 脚本

c# - WinForms 在没有 Form/UserControl 的情况下检索键盘状态