将依赖项注入DelegatingHandler [英] Inject dependency into DelegatingHandler
问题描述
我是依赖注入的新手,但是对Ninject
和Ninject.Extensions.Logging
到[Inject]
我的ILogger
的任何地方都满意.
I am new to dependency injection, but happy with Ninject
and Ninject.Extensions.Logging
to [Inject]
my ILogger
wherever i need it.
但是,某些 DelegatingHandlers 破坏了所有的乐趣.
However some DelegatingHandlers are spoiling all the fun.
public class HttpsHandler : DelegatingHandler
{
[Inject]
public ILogger Logger { get; set; }
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (!string.Equals(request.RequestUri.Scheme, "https", StringComparison.OrdinalIgnoreCase))
{
Logger.Info(String.Format("{0}: is using HTTP", request.RemoteAddress());
return
Task.Factory.StartNew(
() =>
new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("HTTPS Required")
});
}
return base.SendAsync(request, cancellationToken);
}
}
有人可以向我指出如何将Ninject.Extensions.Logger.Nlog2注入到委托处理程序中的Ilogger中的正确方向吗?
Could anyone point me in the right direction on how to Inject Ninject.Extensions.Logger.Nlog2 into Ilogger inside the delegatinghandlers?
更新
我认为Pete在评论中向我指出了正确的方向(谢谢!).
我在HttpsHandler
中添加了以下构造函数:
I think Pete got me in the right direction in the comments (thanks!).
I added the following constructor to the HttpsHandler
:
public HttpsHandler()
{
var kernel = new StandardKernel();
var logfactory = kernel.Get<ILoggerFactory>();
this.Logger = logfactory.GetCurrentClassLogger();
}
现在我的记录仪开始工作了!
and now i've got the Logger working!
我唯一剩下的问题是,这是正确的实现方式,还是反模式?
My only question left, is this the right way to do it, or is it a anti-pattern?
推荐答案
DelegatingHandlers
在应用程序启动时仅在Web API中初始化一次.
DelegatingHandlers
are only initialized once in Web API, at application start.
这是Web API的已知问题/设计功能(出于性能方面的考虑,我认为是这样)-在此处查看错误报告 http://aspnetwebstack.codeplex.com/workitem/62 .
This is a known issue/design feature of Web API (I presume for performance reasons) - see the bug report here http://aspnetwebstack.codeplex.com/workitem/62.
像您自己建议的那样使用构造函数初始化,仅在您具有单例类型的依赖项时才有效(这就是记录器起作用的原因).无论如何,如果要将分辨率委派给Web API DependencyResolver
,则必须使用GetDependencyScope()
(可以从HttpRequestMessage
调用),作为解决方法.
Using a constructor initialization like you suggested yourself, would only work if you have singleton-type dependencies (that' why you logger works). Regardless, if you want to delegate the resolution to Web API DependencyResolver
you have to use GetDependencyScope()
, which can be called off the HttpRequestMessage
, as a workaround.
我发布了如何使用Ninject 前一段时间.您应该使用这种方法来解决您的依赖问题,因为在您当前的解决方案中,您已经将Ninject& amp;您的处理程序,这远非期望.
I posted a walkthrough on doing that with Ninject a while ago. You should use this approach to resolve your deendency, because with your current solution you have coupled Ninject & your handler, which is far from desired.
这篇关于将依赖项注入DelegatingHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!