Самостоятелен хост на Autofac и Web API

Получавам грешката:

„Обхватът на живота на заявката не може да бъде създаден, защото 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-хостинг работи добре, но при използване на самостоятелно хостване IoC с AutoFac се проваля.


person user437899    schedule 28.01.2013    source източник
comment
Моля, бихте ли предоставили повече код?   -  person cuongle    schedule 28.01.2013
comment
Обхват за целия живот.   -  person Steven    schedule 28.01.2013


Отговори (1)


Вие използвате MVC интеграционния пакет на Autofac с 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

person Filip W    schedule 28.01.2013
comment
Ползвам и двете. Но WebApi DependencyResolver също не работи - person user437899; 28.01.2013