This project is read-only.

The XXX is registered as 'Web API Request' lifestyle, but the instance is requested outside the context of a Web API Request

Oct 17, 2014 at 3:19 AM
I use SI in my asp.net web api 2 project,I want get current request's HttpRequestMessage in a utility class.

my code like this:

Application_Start:

var container = new Container();
container.Options.AllowOverridingRegistrations = true;
container.EnableHttpRequestMessageTracking(config);
container.RegisterWebApiRequest<IRequestMessageProvider, RequestMessageProvider>();
container.Verify();
config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);

and I have class to access server:

public class ServiceProvider
{
    private static IDependencyResolver _resolver = GlobalConfiguration.Configuration.DependencyResolver;

    public static T GetService<T>()
    {
        object service = _resolver.GetService(typeof(T));
        return (T)service;
    }

    public static object GetService(Type type)
    {
        object service = _resolver.GetService(type);
        return service;
    }
}
and usage:

IRequestMessageProvider provider = ServiceProvider.GetService<IRequestMessageProvider>();
var currentRequest= provider.CurrentMessage;

I found some request is work fine,but some request not working. A exception throw:

"The IRequestMessageProvider is registered as 'Web API Request' lifestyle, but the instance is requested outside the context of a Web API Request."
Oct 17, 2014 at 7:10 AM
Can you describe when the request succeeds and when you get the exception? And can you post a stack trace?