看来有两个问题需要解决这里:
- 你怎么注册的RequestContext?
- 为什么RequestContext不能正确解析?
,你可以,如果你正在使用Autofac MVC整合登记最容易做的事情是:
目前已经是注册各种网络抽象(HttpContextBase,RequestContext的,等模块)正确的范围为每个HTTP请求实例。它已经过测试,将为您节省大量时间。
如果您想要自己手动注册它,那么如果您将其范围限制为InstancePerHttpRequest(这样您就不会在每个请求中反复获取它),那么应该执行该操作。
此外,您可以在“链”成当前上下文像模块:
builder.Register(c => new HttpContextWrapper(HttpContext.Current))
.As<HttpContextBase>()
.InstancePerHttpRequest();
builder.Register(c => c.Resolve<HttpRequestBase>().RequestContext)
.As<RequestContext>()
.InstancePerHttpRequest();
这需要第一部分的护理,但第二部分是有点棘手。
如果您在应用程序启动时发生错误,因为RequestContext不可用,那么您的应用程序中的某处您尝试在实际请求之前解析使用RequestContext的内容。例如,手动尝试解析具有RequestContext作为构造函数参数的某个HttpModule实现。
注册的lambda实际上并没有得到评估,直到解决,所以错误可能来自你正在尝试使用RequestContext过早解决的问题。
在这种情况下,问题是:当您尝试解析RequestContext并且没有请求时,您希望如何处理解析?
默认情况下,你会得到一个异常,这可能是你现在看到的。
如果你希望它是零,而不是,然后做一个像这样的登记:
// Register context as instance-per-dependency and handle the
// case where it's null. Also handle HttpException because IIS7
// can throw if you access HttpContext.Current too soon in app startup.
builder.Register(
c => {
try
{
var ctx = HttpContext.Current;
return ctx == null ? null : new HttpContextWrapper(ctx);
}
catch(HttpException)
{
return null;
}
}).As<HttpContextBase>();
// RequestContext also gets registered instance-per-dependency
// and handles the null context case.
builder.Register(
c => {
var ctx = c.Resolve<HttpRequestBase>();
return ctx == null ? null : ctx.RequestContext;
}).As<RequestContext>();
这应该让你过去的应用程序,启动问题。
所有这些......你应该找出在应用程序启动时试图使用RequestContext的东西,看看你是否可以修复设计。在正常情况下,你不应该最终需要做这种事情。