Reputation: 1267
I treid to use HttpContext in dataAceess layer but i cant creat a object from HttpContext
HttpContext httpContext = HttpContext.Current;
I creat a web application and a libery project and i want to use HttpContext in libery project like this :
public static Context GetContextPerRequest()
{
HttpContext httpContext = HttpContext.Current;
if (httpContext == null)
{
return new Context();
}
else
{
int contextId = Thread.CurrentContext.ContextID;
int hashCode = httpContext.GetHashCode();
string key = string.Concat(hashCode, contextId);
Context context = httpContext.Items[key] as Context;
if (context == null)
{
context = new Context();
httpContext.Items[key] = context;
}
return context;
}
}
I use .net 4.
Upvotes: 2
Views: 2369
Reputation: 1267
I solve my problem in this way :
Upvotes: -1
Reputation: 364249
I'm not sure what is your question but your code shows some very bad concepts.
What do you expect this will do?
int contextId = Thread.CurrentContext.ContextID;
int hashCode = httpContext.GetHashCode();
string key = string.Concat(hashCode, contextId);
Context context = httpContext.Items[key] as Context;
if (context == null)
{
context = new Context();
httpContext.Items[key] = context;
}
HttpContext
is your safe storage for HTTP request processing in ASP.NET. HttpContext.Current
returns unique instance for every request and this instance is independent on thread processing the request - even in asynchronous processing the HttpContext
will flow with your request from thread to thread but you will never have two threads working on the same request (unless you try to spawn your own threads). If you try to spawn your own threads you cannot use this way at all because HttpContext
instance exists only until the request is processed but your custom thread lifetime can be longer.
So the code you are using is just overcomplicated version of this:
Context context = httpContext.Items["Context"] as Context;
if (context == null)
{
context = new Context();
httpContext.Items["Context"] = context;
}
Also if this code is from your data access layer it is wrong desing. Data access layer deals with data access and should be independent on upper processing - including HTTP request processing. It means that your GetContextPerRequest
method doesn't belong to data access layer.
Upvotes: 1