Asp.net web api Autofac和Web API自宿主

Asp.net web api Autofac和Web API自宿主,asp.net-web-api,autofac,self-hosting,Asp.net Web Api,Autofac,Self Hosting,我得到一个错误: “无法创建请求生存期范围,因为HttpContext 不可用。” 如果我尝试设置我的web api HttpContext在System.Web.Http.SelfHost中不可用,但是否有替代方案 我的AuthenticationHandler示例: public class AuthenticationHandler : DelegatingHandler { private const string m_AuthenticationSche

我得到一个错误:

“无法创建请求生存期范围,因为HttpContext 不可用。”

如果我尝试设置我的web api

HttpContext在System.Web.Http.SelfHost中不可用,但是否有替代方案

我的AuthenticationHandler示例:

    public class AuthenticationHandler : DelegatingHandler
    {
        private const string m_AuthenticationScheme = "Basic";
        protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            AuthenticationHeaderValue authenticationHeader = request.Headers.Authorization; //get the authorization header

            if (authenticationHeader != null && authenticationHeader.Scheme == m_AuthenticationScheme) 
            {
                Credentials credentials = authenticationHeader.ParseAuthenticationHeader();

                if (credentials != null)
                {   
                    IMyClass procadCredentials = DependencyResolver.Current.GetService<IMyClass>(); //thows the InvalidOperationException if I use self-hosting
//tried: "Autofac.Integration.Mvc.AutofacDependencyResolver.Current.RequestLifetimeScope.Resolve<IMyClass>();" too.
公共类AuthenticationHandler:DelegatingHandler
{
私有常量字符串m_AuthenticationScheme=“Basic”;
受保护的重写System.Threading.Tasks.Task SendAsync(HttpRequestMessage请求,System.Threading.CancellationToken CancellationToken)
{
AuthenticationHeaderValue authenticationHeader=request.Headers.Authorization;//获取授权头
if(authenticationHeader!=null&&authenticationHeader.Scheme==m\u AuthenticationScheme)
{
凭据凭据=authenticationHeader.ParseAuthenticationHeader();
如果(凭据!=null)
{   
IMyClass procadCredentials=DependencyResolver.Current.GetService();//如果使用自托管,则显示InvalidOperationException
//尝试过:“Autofac.Integration.Mvc.AutofacDependencyResolver.Current.RequestLifetimeScope.Resolve();”也可以。
我收到了InvalidOperation异常,消息如下:

无法创建请求生存期范围,因为HttpContext 没有

IMyClass在global.asax中注册如下:

m_builder.Register<IMyClass>((c, p) =>
            {
//...
//return ...
}
m_生成器寄存器((c,p)=>
{
//...
//返回。。。
}

IIS托管时工作正常,但使用自托管时,IoC和AutoFac会失败。

您使用的是AutoFac的MVC集成包和Web API,而实际上您应该使用的是
AutoFac.WebApi


您可以在此处阅读更多信息-

请提供更多代码。我两者都使用。但是WebApi依赖解析程序也不起作用