Hi again..
I am here again with the same issue, and this is because a long conversation that I had with Oren Ellenbogen (ex. co-worker) about some extending and refactoring of the former post solution (you can see it here if you missed it).
The main goal in the Session/Application objects encapsulation was the ability of avoiding casting each time that we would use these objects, this is annoying especially we uses the specific object in most of the flows of the application.
The other goal is getting the ability of managing these objects in one centered place.
NOW, some extesibility...
This object need to be maintened everytime that we want to add a new session/application object. Good usage of generics will solve this problem -> this will bring up the ability of adding new objects everywhere that we'll want (example in the continuance...).
So, look at the following implemetation:
public static class SessionRepository
{
public static bool IsExist(string objectKey)
{
return HttpContext.Current.Session[objectKey] != null;
}
public static TObject GetInstance<TObject>(string objectKey)
{
return (TObject)HttpContext.Current.Session[objectKey];
}
public static void Add<TObject>(string objectKey, TObject obj)
{
HttpContext.Current.Session.Add(objectKey, obj);
}
}
Some usage:
if (SessionRepository.IsExist("SomeObjectKey"))
{
SomeObject obj = SessionRepository.GetInstance<SomeObject>("SomeObjectKey");
// Do your things...
}
SessionRepository.Add<SomeObject>("SomeObjectKey", SomeObject);
This way of implementation comes to help us with the casting issue and it gives up extensibilty options. I think that there is a small disadventage here - we also need to remeber the keys of the objects in the session object - but there is nothing perfect.
Summary:
- Both of the solutions are good and each has each advantages/disadventages, you can prefer the best way of using.
- The first way (shown in the former post) enables you a direct access to the object stays in the session/application, but need to be managed for each time we want to add new object into the session/application.
- The way shown here holds a different approach, enables you extensibility, but you don't have the explicit access to these objects.
- In both ways, the casting issue is covered!
That's it for today.
Commets will be appriciated...