Autofac和Web API自托管

时间:2013-01-28 11:42:03

标签: asp.net-web-api autofac self-hosting

我收到错误:

  

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

如果我尝试设置我的网络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.

我收到了带有消息的InvalidOperationException:

  

由于HttpContext,无法创建请求生存期范围   不可用。

IMyClass在global.asax中注册如下:

m_builder.Register<IMyClass>((c, p) =>
            {
//...
//return ...
}

虽然IIS-Hosting,它运行正常,但使用自托管,IoC与AutoFac失败。

1 个答案:

答案 0 :(得分:0)

您正在使用Autofac的MVC集成包与Web API,而您应该真正使用Autofac.WebApi http://nuget.org/packages/Autofac.WebApi

您可以在此处阅读更多相关信息 - http://alexmg.com/post/2012/09/01/New-features-in-the-Autofac-MVC-4-and-Web-API-(Beta)-Integrations.aspx