Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC - How to instantiate, store and make a typed variable available throughout the application, once per page view

I am developing an MVC app to serve multiple domains - each is a branch of a larger company.

A LocalBranch class stores details such as phone, address, email, location coordinates etc.

I want to create a single instance of this class per http request and have it available throughout the application - from within controllers, views, some helper classes and other code.

Is there a recommended way of doing this?

Right now I have it as a property on a BaseController and use ViewBagto pass it to views. But I would prefer it strongly typed in Views if possible.

I don't want to put it in an application variable, because we need to serve different values to different domains.

I would rather avoid a session variable if possible because we might scale up to use multiple servers in the future, and I've heard this doesn't play well with sessions.

Please feel free to update tags / title if you think there is a clearer way of expressing what I'm after. Thank you.

like image 499
Martin Hansen Lennox Avatar asked Jan 27 '15 19:01

Martin Hansen Lennox


People also ask

What is This MVC tutorial for?

This is a beginner tutorial that introduces the basics of ASP.NET MVC. You'll create a simple web application that reads and writes from a database. Visit the ASP.NET MVC learning center to find other ASP.NET MVC tutorials and samples.

How do I create a MVC application in Visual Studio?

Start Visual Studio and select Create a new project. In the Create a new project dialog, select ASP.NET Web Application (.NET Framework) > Next. In the Configure your new project dialog, enter MVC for Project name > Create. In the Create a new ASP.NET Web Application dialog, select MVC > Creat For beginners, you may see details from here.

How to pass data from controller action to view in MVC?

The best and preferred approach in ASP.NET Core MVC to pass data from a controller action method to a view is by using a strongly typed model object. In our example, we are still using ViewBag to pass the Header and Title from the Controller action method to the View.

Can multiple implicitly typed variables be initialized in the same statement?

Multiple implicitly-typed variables cannot be initialized in the same statement. If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration. Implicit typing with the var keyword can only be applied to variables at local method scope.


2 Answers

The best way to maintain your state in a web application per request is simply use the HttpContext class.

You need to store your state(LocalBranch) as an Item in the HttpContext:

HttpContext.Current.Items.Add("LocalBranch", GetLocalBranch());

You can fetch the Item all across your application like this:

LocalBranch branch = HttpContext.Current.Items["LocalBranch"] as LocalBranch;

The Items property is simply a key value Dictionary. The value is an object. You will have to check for nulls and this is really similar to the Session object you know.
The main difference is the scope. The HttpContext is a dot net object that has a lifetime of an http request.

Now using the HttpContext the way I've shown you is the simplest way to do it.

You can go two steps forward and use a framework called Unity and add a lifetime to your objects.
Unity does much more and the lifetime management is just one gem.

You can create a custom HttpContext lifetime that generates objects per request.
Something like this.

And them all you need to do is:

1.Register you LocalBranch class with the HttpContext lifetime.
2.Add a static Current property which will use the Unity container and resolve the correct instance of LocalBranch.
3.Use it something like this: LocalBranch.Current

BTW, you can use Unity's dependency injection for injecting objects into controllers and other modules. That's a better practice then just using the static Current property.

like image 172
Amir Popovich Avatar answered Nov 02 '22 06:11

Amir Popovich


You kind of have two questions here. The first is "How do I create a single instance of this class per HttpRequest?" The second is "How do I make this available to strongly typed views?"

The first has pretty much been answered by @amir-popovich to use dependency injection. However, FWIW I would probably use Ninject instead of Unity (just preference, really) and I would probably implement it differently. I would not use HttpContext, and simply build a service (which is instanciated using Ninject's OnePerHttpRequest Module, passing the domain as an argument to get the proper values).

Then, in order to add these LocalBranch values to your strongly typed View Model, you can first create a base view model which holds this type:

public class BaseViewModel
{
    public LocalBranch Branch {get;set;}
}

Then, make all of your current view models inherit this base type

public MyViewModel : BaseViewModel
{
    public string SomeValue {get;set;}
}

Then in your controller, it is easy enough to add these values from the service you created from the first step

public ActionResult SomeAction()
{
    var vm = new MyViewModel();
    vm.Branch = LocalBranchService.GetLocalBranchValues(); //Local Branch Service has been injected with Ninject

    //do other stuff

    return View(vm);
}

However, that gets pretty tedious to add that to each controller action, so you can instead create a Result Filter to add it for you:

public class LocalBranchResultFilter : FilterAttribute, IResultFilter 
{
    public void OnResultExecuting(ResultExecutingContext filterContext)
    {
        //This method gets invoked before the ActionResult is executed.
        filterContext.Controller.ViewData.Model.Branch = LocalBranchService.GetLocalBranchValues(); //Local Branch Service has been injected with Ninject
    } 
}

Now, you can just decorate your Controller and/or Actions with the filter (you could even set it in the Global Filters if you want).

like image 21
solidau Avatar answered Nov 02 '22 06:11

solidau