我有一个自定义 HttpModule ,我在其中跟踪 http 请求,部分实现如下;
private readonly HttpContextBase _httpContext;
private readonly ISessionContext _sessionContext;
public ASHttpModule(HttpContextBase httpContext,
ISessionContext sessionContext)
{
this._httpContext = httpContext;
this._sessionContext = sessionContext;
}
public void Init(HttpApplication context)
{
context.BeginRequest += Context_BeginRequest;
context.EndRequest += Context_EndRequest;
}
private void Context_BeginRequest(object sender, EventArgs e)
{
Stopwatch stopwatch = new Stopwatch();
_httpContext.Items["Stopwatch"] = stopwatch;
stopwatch.Start();
}
private void Context_EndRequest(object sender, EventArgs e)
{
Stopwatch stopwatch = (Stopwatch)_httpContext.Items["Stopwatch"];
if (stopwatch == null)
return;
stopwatch.Stop();
TimeSpan ts = stopwatch.Elapsed;
//Check current httprequest variables and log if have to
}
这是我的依赖注册(使用 Autofac);
builder.RegisterType<WebSessionContext>()
.As<ISessionContext>().InstancePerRequest();
builder.Register(c => (new HttpContextWrapper(HttpContext.Current) as HttpContextBase))
.As<HttpContextBase>()
.InstancePerRequest();
builder.Register(c => c.Resolve<HttpContextBase>().Request)
.As<HttpRequestBase>()
.InstancePerRequest();
builder.Register(c => c.Resolve<HttpContextBase>().Server)
.As<HttpServerUtilityBase>()
.InstancePerRequest();
builder.Register(c => c.Resolve<HttpContextBase>().Session)
.As<HttpSessionStateBase>()
.InstancePerRequest();
这里的问题是 HttpModule 只构造一次,而 HttpContext 需要为每个请求注入。我找到的解决方案是使用 DependencyResolver 作为;
HttpContextBase _httpContext = DependencyResolver.Current.GetService<HttpContextBase>();
但是,我想避免这种用法,因为 ServiceLocator 被认为是反模式。
有没有不使用 DependencyResolver 将 HttpContext 注入 HttpModule 的解决方案?