Introduction

In my previous post we discussed an approach to access the HttpContext.Session in RequestHandler. However, there was a problem. For every single component where we need to access the session, we have to inject a dependency of IHttpContextAccessor. While for one or two components it’s not a problem, it can be very daunting if we have to do the same over and over again. In this article, we will use a different approach to achieve the same.

 

The AppContext

In this approach, we are going to create a static AppContext class. This class going to hold the current Http session as a property called Current. In our previous approach, we used the IHttpContextAccessor to get the current Http session, likewise we are gonna do here. However, since I want to keep the AppContext static, we need a static method to inject IHttpContextAccessor to it, as shown in the code below:

 

The Startup Class

The Startup class in this case will be a little different from the previous one. We still need to add the IHttpContextAccessor to the ConfigureServices method. It is the ConfigureService method where we will inject the IHttpContextAccessor into the AppContext. And, to achieve that we are going to use the IApplicationBuilder as shown below:

 

ISession Extensions

Just for fun, I added a few extension methods for ISession though it’s not really required. But if you find them useful, go ahead to consume them in a real life project:

 

The RequestHandler and HomeController

Now that we have the setup ready, it’s time to set the message in our RequestHandler using the AppContext which gives us the current session. We can then get the mesage from the session in the controller, as we did in our previous approach. Please refer to the code below:

 

Summary

If I compare this approach with the previous one, this one feels much cleaner. I would be more than happy to know what you guys think about the two. Which one would you choose and why? Please do let me know in the comments below.

If you have not read my previous article discussing the first approach, you can find the same here.

 

Categories: .Net Core

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.