gpt4 book ai didi

c# - Autofac - DelegatingHandler (HttpMessageHandler) 注册

转载 作者:行者123 更新时间:2023-11-30 13:36:41 25 4
gpt4 key购买 nike

我在类库中有一个自定义的 DelegatingHandler,我需要用 Autofac 注册它。 webapi 宿主解决了它对运行时的依赖,因此宿主没有对该库的引用。

public class LocalizationHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken )
{}
}

在我的 Autofac 初始化器类上,我尝试过类似的东西:

protected override void Load( ContainerBuilder builder )
{
builder.RegisterType<LocalizationHandler>();
builder.Register(c => new LocalizationHandler());
}

在主机中注册此类处理程序的正常方法是:

public static void Register(HttpConfiguration httpConfiguration)
{
httpConfiguration.MapHttpAttributeRoutes();
httpConfiguration.MessageHandlers.Add(new LocalizationHandler());
}

但我无权访问此处的宿主项目。关于如何通过 ContainerBuilder 注入(inject)处理程序有什么想法吗?

最佳答案

看来你不能在Web API中注入(inject)HttpMessageHandler

Given the message handler is passed as instance and being initialized once for the entire service. I think it is easier to have user code inject the dependency themselves first and register the instance with http configuration. This allow people to write custom message handler that has constructor but do not need dependency injection as well. The current model is more flexible.

>> http://aspnetwebstack.codeplex.com/workitem/62

但是你可以创建代理来做你想做的事。例如:

public class ProxyDelegatingHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
IEnumerable<DelegatingHandler> innerHandlers =
request.GetDependencyScope()
.GetServices(typeof(DelegatingHandler))
.OfType<DelegatingHandler>();

HttpMessageHandler handler = this.InnerHandler;
foreach (DelegatingHandler innerHandler in innerHandlers)
{
innerHandler.InnerHandler = handler;
handler = innerHandler;
}

HttpMessageInvoker invoker = new HttpMessageInvoker(handler, false);
return invoker.SendAsync(request, cancellationToken);
}
}

然后像这样注册你的处理程序:

        builder.RegisterType<X1Handler>().As<DelegatingHandler>().InstancePerRequest();
builder.RegisterType<X2Handler>().As<DelegatingHandler>().InstancePerRequest();

config.MessageHandlers.Add(new ProxyDelegatingHandler());

关于c# - Autofac - DelegatingHandler (HttpMessageHandler) 注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30845632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com