Search code examples
c#asp.net-mvc-4asynccontroller

Unable to access the HttpContext or Request object in the constructor of an AsyncController


I am using an AsyncController say 'AbstractAbcContoller'

public class AbstractAbcContoller : AsyncController
{
}

and then I have 3 more controllers which inherit the newly created AbstractAbcContoller.

Now when I create a constructor of any of these 3 controllers and try to access HttpContext/Request objects, I always get them as null.

I need to initialize my service objects which accept the HttpRequestBase as an argument in its constructor.

I had to settle for this workaround instead.

public class AbstractAbcController : AsyncController
{
    protected IAbcService GetAbcService(AbstractAbcController controller, HttpRequestBase request)
    {
        if (controller.GetType() == typeof (AbcAddressVerificationController))
            return new AbcAddressVerificationService(request);

        if (controller.GetType() == typeof(AbcPhoneVerificationController))
            return new AbcPhoneVerificationService(request);

        throw new ArgumentException();
    }
}

and then in controller/action use something like this

IAbcService abcService = GetAbcService(this, Request);
abcService.DoSomething();

which I kinda don't like, i am not sure which would be a better way. Please advice.


Solution

  • Request and Response Context are per request objects and a separate copy is available to each request context, so no point in injecting them through Constructor so instead they should be passed a parameter of each method that requires them