Custom session store in ASP.NET MVC with Dependency Injection

In this post I will explain creating custom session helper with Unity DI.

Step 1

Create empty MVC project

Step 2

Add new folder called Utility and Add a interface with name of ISession. In a real project we can separate this logic into another project.

ISession interface


 T Get<T>(string key);
 void Set<T>(string key, T entry);

Step 3

Add a class called CustomSessionStore and implement ISession interface.

Add following logic to class.


public T Get<T>(string key)
 {
 HttpContext currentContext = GetSessionContext();

return (T)currentContext.Session[key];
 }

public void Set<T>(string key, T entry)
 {
 HttpContext currentContext = GetSessionContext();
 currentContext.Session[key] = entry;
 }
 private static HttpContext GetSessionContext()
 {
 HttpContext currentContext = HttpContext.Current;

if (currentContext == null)
 {
 throw new InvalidOperationException();
 }
 return currentContext;
 }

we have to add System.Web reference in top of page

using System.Web;

Step 4

Add Unity.MVC to project via nuget package manager

unity

Then we can see Two new classes inside App_Start folder

unityclasses

In UnityConfig.cs we can register dependecy as below.

registerTypes

Step 5

The add a controller called HomeController and implement as below

 

homecontroller

So as above we can easily set value to session using Set method. We can store any type of values since it is generic. Only thing we have to provide is type when saving and retrieving values as shown as above.

Source code

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s