Best practice in this situation and (similar situations) is to implement a DI/IoC pattern
, as @Dawid-Ferenczy mentioned in his answer. if you never worked with it before , it's a little abstract at the beginning but it's very useful in the long run , especially if your objects got complicated. You can search online for articles to learn more about the pattern itself.
@Dawid-Ferenczy mentioned the Unity container, but it's not limited to that , you can use any container you would like (Or even create your own if you need to ).
I personally use Ninject as it has a has a lot of support documentation and i found it easy to implement.
In your case (DB context) i would use Ninject
and DI/IoC
as follow:
1- Declare an interface for your DB Context DAL:
public interface IModelDBContext
{
//Your methods should go here
}
Your concrete class:
public class ModelDBContext : DbContext,IModelDBContext
{
//Your methods and other stuff here
}
Container part
(Ninject in my case , but you can use any other container)
public class NinjectDependencyResolver : IDependencyResolver
{
//Bunch of initialization and methods
Check out this : [Using ninject in MVC][2].
//Binding piece (Very important)
private void AddBindings()
{
//Context DB Binding
kernel.Bind<IModelDBContext>().To<ModelDBContext>();
//Other binding
}
}
Implementation part:
This is the fun and exciting part. anywhere in your application , if you need to implement your specific DB context you inject it with the constructor and it will be available for you to use:
In your case it will be something like this:
Public YourConcreteClass
{
Private IModelDBContext ModelDB; //Initiate an instance that you will use .
//DI by constructor
public YourConcreteClass(IModelDBContext mDB)
{
ModelDB=mDB;
}
//in the rest of your code you call ModelDB that has access to all of the methods and attributes you might need
}