You have two questions. First: "How to create one instance of this class for HttpRequest?" The second way: "How to make it available for strongly typed views?"
The first was pretty @ amir-popovich's answer to use dependency injection. However, FWIW I would probably use Ninject instead of Unity (just a preference, really), and I would probably use it differently. I would not use HttpContext and just create a service (which starts using the Ninject OnePerHttpRequest module, passing the domain as an argument to get the correct values).
Then, to add these LocalBranch values ββto a strongly typed view model, you can first create a base view model that contains this type:
public class BaseViewModel { public LocalBranch Branch {get;set;} }
Then make all your current view models inherit this base type
public MyViewModel : BaseViewModel { public string SomeValue {get;set;} }
Then, in your controller, it is enough to simply add these values ββfrom the service created from the first step.
public ActionResult SomeAction() { var vm = new MyViewModel(); vm.Branch = LocalBranchService.GetLocalBranchValues();
However, it is rather tedious to add this to every 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) {
Now you can simply decorate your controller and / or actions with a filter (you can even set it in global filters if you want).
source share