c# - WebApi - Autofac 无法解析参数 HttpRequestMessage

标签 c# asp.net-web-api asp.net-web-api2 autofac

我遇到 RegisterHttpRequestMessage 不适用于我的问题,并且无法弄清楚我做错了什么。特别是当我尝试手动解析接受 HttpMessageRequest 作为参数的服务时。

我正在使用模块在我的构建器中注册组件,目前主 Web 项目中的模块如下所示:

builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

builder.RegisterHttpRequestMessage(GlobalConfiguration.Configuration);
builder.RegisterType<SourceSystemViewModel>().AsImplementedInterfaces().InstancePerRequest();

builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
            .Where(t => t.Name.EndsWith("ViewModelValidator"))
            .AsImplementedInterfaces()
            .PropertiesAutowired();
// Etc etc etc

SourceSystemViewModel 目前非常简单,如下所示:

public interface ISourceSystemViewModel
{
    SourceSystem Value { get; }
}
public class SourceSystemViewModel : ISourceSystemViewModel
{
    public SourceSystemViewModel(HttpRequestMessage request)
    {
        Value = request.Headers.GetSourceSystem();
    }
    public SourceSystem Value { get; }
}

GetSourceSystem 只是一个提取 header 值的扩展方法。我尝试过使用和不使用 InstancePerRequest 注册 SourceSystemViewModel ,但没有什么区别。当 autofac 尝试解析 ISourceSystemViewModal (最终解析 HttpRequestMessage)时,它会抛出以下错误:

An exception of type 'Autofac.Core.Registration.ComponentNotRegisteredException' occurred in Autofac.dll but was not handled in user code

Additional information: The requested service 'System.Net.Http.HttpRequestMessage' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.

使用autofac 3.5(webapi dll引用为autofac.webapi2 3.4)。

非常感谢任何想法!

注释

我会在遇到任何发现时添加它们......

更新1

我查看了 RegisterHttpRequestMessage 的工作原理,它确实向 HttpConfiguration 添加了一个名为 CurrentRequestHandler 的消息处理程序。当我的请求到来时,我可以看到该消息处理程序仍然存在。所以该方法似乎做了它应该做的事情,它只是没有为我解析请求消息......

更新2

我注意到,在 Controller 的上下文中,因此可以访问HttpRequestMessage,我可以解析这两个对象。像这样:

ILifetimeScope requestLifetimeScope = Request.GetDependencyScope().GetRequestLifetimeScope();
var h = requestLifetimeScope.Resolve<HttpRequestMessage>();
var sourceSystemViewModel = requestLifetimeScope.Resolve<ISourceSystemViewModel>();

更新3

值得注意的是,我正在手动尝试解析期望 HttpMessageRequest 作为注入(inject)参数的服务。例如,这对我来说失败了:

using (var httpRequestScope = IocProxy.Container.Context.BeginLifetimeScope("AutofacWebRequest"))
{
    var sourceSystemViewModel = httpRequestScope.Resolve<ISourceSystemViewModel>();
}

最佳答案

我遇到了同样的问题,基于 SO我能够让它工作

    public class NLoggerTraceWriterModule : Module
{

    private HttpConfiguration _config;

    public NLoggerTraceWriterModule(HttpConfiguration config)
    {
        this._config = config;
    }

    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterInstance(this._config).As<HttpConfiguration>();
        builder.Register(c =>
                           c.Resolve<HttpConfiguration>()
                            .Services
                            .GetService(typeof(ITraceWriter)) as ITraceWriter)
               .As<ITraceWriter>();
    }
}

将此模块注册为

// Call RegisterHttpRequestMessage to add the feature.
builder.RegisterHttpRequestMessage(config);
builder.RegisterModule(new Helper.Logging.NLoggerTraceWriterModule(config));

关于c# - WebApi - Autofac 无法解析参数 HttpRequestMessage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37004405/

相关文章:

c# - 从 Web Api 2 IAuthenticationFilter AuthenticateAsync 方法设置 cookie

c# - Odata如何授权用户角色的$expand功能?

c# - 使 CORS 与 Web API 2 一起工作时遇到问题

c# - 在 WPF 控件可见性更改上应用动画

c# - 指定的初始化向量 (IV) 与该算法的 block 大小不匹配

c# - 如何在列表框(asp.net)中添加复选框?

c# - 路由模板分隔符 '/'不能连续出现-属性路由问题

asp.net - 在 IIS 7.5 中为每个应用程序池设置 CLRConfig 文件

c# - 如何在 .Net Core 中要求非匿名用户?

azure - Azure Web API 的身份验证 token