依赖注入 HTTPModule
Google/MyBrain 让我失望了。 如果不使用框架(我永远不会超越我的同事),鉴于您(程序员)无法控制创建实例,如何将依赖项注入到 HTTPModule 中?
我们是否要修改自定义 web.config 部分 + 反射,或者是否有一些我没有看到的更干净的东西?
例如使用 Karl Seguin 的 示例 模块作为基础,并假设实现了 ILogger。 .Net 2.0 fwiw
public class ErrorModule : IHttpModule
{
private ILogger injectedLogger; //how to set this?
public void Init(HttpApplication application)
{
application.Error += (new EventHandler(this.application_Error));
}
public void Dispose() { /* required by IHttpModule */ }
private void application_Error(object sender, EventArgs e)
{
this.injectedLogger.doStuff(e.ExceptionObject as Exception);
}
}
正是这样的事情让我意识到我是多么鄙视 MSDN。
Google/MyBrain are failing me. Without using a framework (which I'll never get past my colleagues), how do you inject a dependency into an HTTPModule given that you (the programmer) are not in control of creating the instance?
Are we into hacking up custom web.config sections + reflection or is there something cleaner I'm not seeing?
e.g. using Karl Seguin's example module as a base, and assuming the implementation of an ILogger. .Net 2.0 fwiw
public class ErrorModule : IHttpModule
{
private ILogger injectedLogger; //how to set this?
public void Init(HttpApplication application)
{
application.Error += (new EventHandler(this.application_Error));
}
public void Dispose() { /* required by IHttpModule */ }
private void application_Error(object sender, EventArgs e)
{
this.injectedLogger.doStuff(e.ExceptionObject as Exception);
}
}
It's things like this make me realise how much I despise MSDN.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我偶然发现了一个程序化的解决方案。 完全消除 web.config 引用,如果您小心生命周期,您可以将模块添加到 global.asax 中。
在global.asax中添加:
其中“LogImplementer”实现了ILogger,只需向httpmodule添加一个构造函数即可:
有一些健康警告。 您必须非常小心在 global.asax 中执行此操作的位置(我很确定 Init() 是正确的,但我不确定)并且该模块不会添加到只读 HttpApplication.Modules 集合中。 除此之外,效果很好。
I've stumbled on a programatic solution. Eliminating web.config references entirely, you can add a module into global.asax if you're careful with the life-cycle.
In global.asax add:
where "LogImplementer" implements ILogger, and just add a constructor to the httpmodule:
There are some health warnings. You have to be really careful about where you do this int he global.asax (I'm pretty sure that Init() is right, but I'm not certain) and the module isn't added to the readonly HttpApplication.Modules collection. Other than that, works beautifully.
您可以使用非常简单的一类 ioc 15 分钟 33 行的 IoC 容器
You can use a very simple one-class ioc An IoC Container In 15 Minutes and 33 Lines
请查看我对类似问题的回答:
IoC 依赖项注入自定义 HTTP 模块 - 如何? (ASP.NET)
Please take a look at my answer here on similar question:
IoC Dependancy injection into Custom HTTP Module - how? (ASP.NET)