我有一项服务,要求在施工期间传递UserName
。 UserName
将来自当前的Web请求cookie或查询字符串。
builder.Register((c,p) => {
var accessService = c.Resolve<IAccessService>();
var access = accessService.GetBySite(Request.QueryString["username"]);
return new JsonWebRequest(access.Site, access.Token);
}).InstancePerRequest();
我尝试按上述方式注册,但收到此错误消息
请求在此上下文中不可用
答案 0 :(得分:4)
您应该使用HttpContext.Current
来访问活动上下文中的信息。
builder.Register((c,p) => {
var accessService = c.Resolve<IAccessService>();
var request = HttpContext.Current.Request;
var access = accessService.GetBySite(request.QueryString["username"]);
return new JsonWebRequest(access.Site, access.Token);
}).InstancePerRequest();
另一种方法是使用AutofacWebTypesModule
导入HttpRequestBase
的注册。使用Autofac MVC5 nuget package
builder.RegisterModule<AutofacWebTypesModule>();
builder.Register((c,p) => {
var accessService = c.Resolve<IAccessService>();
var request = c.Resolve<HttpRequestBase>();
var access = accessService.GetBySite(request.QueryString["username"]);
return new JsonWebRequest(access.Site, access.Token);
}).InstancePerRequest();
顺便说一句,出于测试目的和更大的灵活性,我建议您创建一个IUserNameProvider
界面来获取用户名
public interface IUserNameProvider
{
String UserName { get; }
}
public class QueryStringUserNameProvider
{
public QueryStringUserNameProvider(HttpRequestBase request)
{
this._request = request;
}
private readonly HttpRequestBase _request;
public String UserName
{
get
{
return this._request.QueryString["UserName"];
}
}
}
你可以像这样使用它:
builder.RegisterModule<AutofacWebTypesModule>();
builder.RegisterType<QueryStringUserNameProvider>()
.As<IUserNameProvider>()
.InstancePerRequest();
builder.Register((c,p) => {
var accessService = c.Resolve<IAccessService>();
var userNameProvider = c.Resolve<IUserNameProvider>();
var access = accessService.GetBySite(userNameProvider.UserName);
return new JsonWebRequest(access.Site, access.Token);
}).InstancePerRequest();