在HttpHandler中使用IoC的Construtor / Setter注入是可能的吗? [英] Construtor/Setter Injection using IoC in HttpHandler, is it possible?

查看:302
本文介绍了在HttpHandler中使用IoC的Construtor / Setter注入是可能的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个相当毛病的问题。可能有一个简单的解决方案,但我找不到它!



我有一个自定义的HttpHandler,我想处理一个请求,记录某些信息,然后输入数据库中的细节。我正在使用NUnit和Castle Windsor。



所以我有两个接口;一个用于记录另一个数据输入,这是注入的构造函数。我很快发现,没有办法调用构造函数,因为默认的无参数构造函数总是被调用。



所以我以为我会使用Setter注入,并将Castle windsor梳理出来。这实际上就是当我使用 container.Resolve< CustomHttpHandler>(); 我可以检查记录器不是空。 (在Global.asax.cs中的Application_Start中)



问题是虽然Castle Windsor可以创建http应用程序不使用的实例吗?我认为??



基本上,这样做的全部原因是能够通过嘲笑和单元测试隔离测试记录器和数据存储库代码。 p>

任何想法如何解决这个问题?



谢谢!

解决方案

不可能,至少不直接。 IHttpHandler对象由ASP.NET运行时实例化,它不允许Windsor参与其创建。您可以:




  • 通过使用容器作为服务定位器来拉取依赖项。

  • 设置建立一个基础处理程序,创建,注入和委托给您自己的处理程序(请参阅 Spring做它

  • 使用容器作为处理整个请求的另一个服务的服务定位器(如 saret说明


I've ran into a rather hairy problem. There is probably a simple solution to this but I can't find it!

I have a custom HttpHandler that I want to process a request, log certain info then enter the details in the database. I'm using NUnit and Castle Windsor.

So I have two interfaces; one for logging the other for data entry, which are constructor injected. I quickly found out that there is no way to call the constructor as the default parameterless constructor is always called instead.

So I thought I would use Setter injection and let Castle windsor sort it out. This actually works as when I use container.Resolve<CustomHttpHandler>(); I can check that the logger is not null. (In Application_Start in Global.asax.cs)

The problem is although Castle Windsor can create the instance the http application is not using it??? I think??

Basically the whole reason for doing it this way was to be able to test the logger and data repository code in isolation via mocking and unit testing.

Any ideas how I can go about solving this problem?

Thanks!

解决方案

Not possible, at least not directly. IHttpHandler objects are instantiated by the ASP.NET runtime and it doesn't allow Windsor to get involved in its creation. You can either:

  • Pull dependencies, by using the container as a service locator.
  • Set up a base handler that creates, injects and delegates to your own handlers (see how Spring does it)
  • Use the container as a service locator for another service that handles the entire request (as saret explained)

这篇关于在HttpHandler中使用IoC的Construtor / Setter注入是可能的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆