Hi,
I created a class library that has all my classes, business logic and my database access layer code in it.
Now I tried using it in a console application and I ran into a problem, when doing this like: Users.GetSalesHistory();
My code sometimes first checks if it is in cache, if it is, return the results. If its not it cache, it then gets a fresh copy from the database.
problem is, Console applications don't really have a HttpContext.
In other cases, I might check the HttpContext.Current.Request.Items collection, which again a console application doesn't ahve access too.
What can I do to fix my class library?
Any other tips for things to watch out for? Its all about dependencies and assuming they are their!

1 answers
There are a couple of things you can do.
A. Import System.Web into your class, this will give you access to HttpContext if its available to the application you are working with. You will be able to access this object through this path System.Web.HttpContext.
B. The preferred option is to pass in the HttpContext into your class method or using a class property. Example passing object to a method:
...
//calling code
string[] _Results = MyClass.ReturnAllServerVariableKeys(Page.Request);
//the class method
public string[] ReturnAllServerVariableKeys(System.Web.HttpRequest _Request)
{
return _Request.ServerVariables.AllKeys();
}
.....
Hope this helps.
answered 2 years ago by:
0
One other thing. My above suggestion will allow your class library to compile however you will not be able to use your System.Web methods and properties within a console application since you won't be running it through a web server.
If you need to use the same method shared among a web app and console app I would do something like this:
CALLING CODE
//console app
Test.SharedMethod(null, ...);
//web app
Test.SharedMethod(Page.Request, ...);
CLASS CODE
class Test
{
SharedMethod(HttpRequest _HR, ...)
{
if(_HR == null)
//this is your console app
else
//this is your web app
}
}
Does this make sense to you?
answered 2 years ago by:
0
Yes it does, is that all the options I have? hehe
So basically it will skip the 'per request cache' every time in a console application since HttpContext.items will always be null (which is expected behavior I guess!).
It seems like a hack though, I mean importing a namespace that won't even work in the environment!
answered 2 years ago by:
0
This post was imported from csharpfriends, if you have a similiar question please ask it again.
All previous members have been migrated, hope you enjoy the new platform!