无法访问AsyncController的构造函数中的HttpContext或Request对象

时间:2015-05-26 07:17:33

标签: c# asp.net-mvc-4 asynccontroller

我正在使用AsyncController说' AbstractAbcContoller'

public class AbstractAbcContoller : AsyncController
{
}

然后我还有3个控制器继承了新创建的AbstractAbcContoller

现在,当我创建这三个控制器中的任何一个的构造函数并尝试访问HttpContext / Request对象时,我总是将它们作为null。

我需要初始化我的服务对象,它接受HttpRequestBase作为其构造函数中的参数。

我不得不接受这种解决方法。

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();
    }
}

然后在控制器/动作中使用类似这样的东西

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

我有点不喜欢,我不确定哪种方式更好。请指教。

1 个答案:

答案 0 :(得分:3)

请求和响应上下文是每个请求对象,并且每个请求上下文都有一个单独的副本,因此通过构造函数注入它们没有意义,因此应该传递每个需要它们的方法的参数