InfoLearner
InfoLearner

Reputation: 15598

.Net how should i share session objects between different layers of asp.net project

I have created a List objects when application starts and saved them as a session variable.

I then use this session variable throughout life of the application.

At times I update to this List in other layers of the application so I want to pass this session variable to other layers.

Should I be passing List object from asp.net to other layers in the methods? should i create a property of List in all layers which are going to use this object and set the property from the presentation layer? if i create a static list then all users see same list. i want the list to be session specific.

Upvotes: 1

Views: 3679

Answers (4)

ChrisLively
ChrisLively

Reputation: 88072

Do not send a session object to your data layers or other business logic. One of the primary reasons for even separating those things out is so that you can reuse the code in other programs.

As soon as you add a dependency, like on HttpContext, then you may as well not have those layers and just throw it all together.

Regarding the list itself, when you need to pass the data to the business / data layers send it as a List.

Finally, I would suggest that unless that list is used on a large number of the pages that you don't put it in session at all and instead just pull the data from the database whenever it's needed. Session data has to be serialized and deserialized on each page access. This adds processing overhead. It gets worse if your app is in a load balanced environment because the session data would have to be pushed and pulled across the network wire for every page access whether or not it was used... which neatly takes away any reason for having it in session anyway.

However, if the data is used in most places then I'm really curious as to what it is. Session shouldn't be used as a dumping ground for a bunch of objects. And I'm really hoping you are not trying to store things like datasets, command objects, or anything like that.

Upvotes: 4

Kunal
Kunal

Reputation: 1943

I will never use Session variables in DataAccess Layer or Business Layer. It's like going against the design. I will rather pass a value of the session variable in the function's parameter in the Data Access Layer or Business Layer which intents to use that Session variable

Upvotes: 1

Chris Van Opstal
Chris Van Opstal

Reputation: 37567

I would write the other layers of your application to accept and return list of objects, they shouldn't be aware or care that the list is being stored after they're done with it.

Upvotes: 4

platon
platon

Reputation: 5340

Your Session variable is available using the following code:

HttpContext.Current.Session[....]

So, you need to create an additional properly only to reduce the code.

Upvotes: 0

Related Questions