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!!

6
  • I think this answer could help u Salut! stackoverflow.com/questions/5118610/… Commented Dec 8, 2014 at 10:34
  • The link in the previous comment is your answer. But beware, your creating a God class, this is the start of a maintenance nightmare. Change your design while you still can! Use dependency injection instead. Commented Dec 8, 2014 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 Commented Dec 8, 2014 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 Commented Dec 8, 2014 at 11:26
  • I recommend learning about dependency injection and IoC-Containers. Commented Dec 8, 2014 at 11:34

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.