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
Then we can see Two new classes inside App_Start folder
In UnityConfig.cs we can register dependecy as below.
Step 5
The add a controller called HomeController and implement as below
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.