静态初始化设计思路
目前,我的 MVC 3 应用程序依赖于在 Application_Start() 中初始化的静态类,如下所示:
protected void Application_Start()
{
MyDependency.Initialize();
}
静态类看起来或多或少类似于以下内容:
public static class MyDependency
{
public static void Initialize()
{
// Perform some I/O...
}
}
此依赖项在属性类中使用,该属性类带有警告没有运行时依赖项(因此在 Application_Start() 中调用初始化)
public class MyAttributeClass : ...
{
public MyAttributeClass()
{
MyDependency.DoSomething(); //...
}
}
最终,我们商店中的其他开发人员将不得不使用这个 API,我想看看是否有办法摆脱这一行在Application_Start()(Global.asax 中的额外代码行可能是一个被遗忘的步骤)
例如,是否有一种方法可以将 MyDependency 类“挂钩”到管道中,而无需编辑 Global.asax?
Currently, my MVC 3 app has a dependency on a static class that is initialized in the Application_Start() like this:
protected void Application_Start()
{
MyDependency.Initialize();
}
With the static class looking more or less like the following:
public static class MyDependency
{
public static void Initialize()
{
// Perform some I/O...
}
}
This dependency is used in an attribute class, which comes with the caveat of having no run-time dependencies (hence the call to initialize in the Application_Start())
public class MyAttributeClass : ...
{
public MyAttributeClass()
{
MyDependency.DoSomething(); //...
}
}
Ultimately, other developers in our shop will have to use this API, and I'd like to see if there's a way to get rid of the line in the Application_Start() (an extra line of code in the Global.asax is likely to be a forgotten step)
For instance, is there a way the MyDependency class can "hook" into the pipeline without the needing to edit the Global.asax?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该查看 WebActivator。来自 wiki:
本质上,你需要类似的东西:
You should look at WebActivator. From the wiki:
Essentially, you'll need something like:
在
MyDependency
中使用静态构造函数。 这里 MSDN 解释了静态功能构造函数提供。通过使用静态构造函数,您应该能够执行所需的所有 IO,因为构造函数将在访问任何静态成员之前运行。
Use a static constructor in
MyDependency
. Here's the MSDN explaining the functionality static constructors provide.By using a static constructor you should then be able to perform all the IO you need, as the constructor will be run before any static members are accessed.