0

I went through many links but couldn't find my answer.Links such as Global variables for setting configurations ASP.NET MVC , ASP.NET MVC C# global variable, ASP.NET MVC Global Variables and many more all of them suggest some complex methods like using Application_Start or using session variables, singleton pattern. But I don't want to use these, I just want declare a variable in a certain file and access it anywhere I need.

var dataContext = new PetaPoco.Database("MessageEntity");

This line is required anywhere I need to access the database. So I want to declare this dataContext as global variable in a certain different file and access it on my several other controllers. How would I accomplish this. Please help!!

Community
  • 1
  • 1
khushbu
  • 567
  • 2
  • 8
  • 24
  • I think this answer could help u Salut! http://stackoverflow.com/questions/5118610/asp-net-mvc-global-variables – Enrique Quero Dec 08 '14 at 10:34
  • The link in the previous comment is your answer. But beware, your creating a [God class](http://en.wikipedia.org/wiki/God_object), this is the start of a maintenance nightmare. Change your design while you still can! Use dependency injection instead. – Ric .Net Dec 08 '14 at 10:40
  • Ok If Its such a bad programming practice, I may not use it. But want to know how it is done. I wrote a separate class public static class DatabaseEntity { public DatabaseEntity() { var dataContext = new PetaPoco.Database("MessageEntity"); } } Now how will I use this class elsewhere – khushbu Dec 08 '14 at 10:57
  • Why is this needing to be done? What are you trying to achieve by having a variable globally set?? Also, you should try the configuration file, `web.config` – Callum Linington Dec 08 '14 at 11:26
  • I recommend learning about dependency injection and IoC-Containers. – CodesInChaos Dec 08 '14 at 11:34
  • I just want to declare the database entity at one place and use it every where else for that do I need dependency injection? – khushbu Dec 14 '14 at 09:31

1 Answers1

0

to create global variable:

public static class Global
{
    public volatile static Object GlobalVariable;
}

It can be accessed everywhere from apllication thru Global.GlobalVariable.

but it is bad solution for data access context.

aleha_84
  • 8,309
  • 2
  • 38
  • 46