I am working on a project and using N-Layer architecture (web layer, service layer, data access layer).
I am facing an issue regarding the use of session storage in the data access layer.
I am storing data in the web layer (controller) and I want to use the session stored data in data access layer. Is this possible? If yes then please let me know...
Thanks in advance.
Shortly: this is possible.
Easy (and really bad) way is to reference web libraries in your data layer and use
HttpContext.Current.Session
. This will break all the flexibility you got before with your code structure when separating layers.A bit longer (but much nicer way) is to install some IOC container. It will allow to declare some interfaces in data layer, and register session providers in the presentation layer.
I am going to show the workflow with Ninject. For example, you have some service (
SomeService
) in the data layer, that needs to operate on data from session. We can use abstractions sinceSomeService
does not really care about origin of the data, it is not that important.Lets move on to presentation layer. Now we should create implementation for our interface from data layer.
Finally, we need to configure dependency injection to use our implementation, whenever
ISomeDataProvider
is used in the constructor. There are plenty of articles about installing Ninject on the web, I recommendNinject.MVC3
package. Once you install it, you will haveNinjectWebCommon.cs
look something similar to this.What is the most important here is this line
kernel.Bind<ISomeDataProvider>().To<SessionDataProvider>().InRequestScope();
. It will configureSomeService
to useSessionDataProvider
in data layer without actually referencing all the web dlls in the data layer and bypassing circular dependencyFinally, inject your service in the controller`s constructor