Injection injection definitely sounds like you are here. My preference is ninject, so the following is an example of how I do this with EF.
Install Ninject.MVC3 (available on nuget)
Go to \ app_start \ NinjectWebCommon.cs (added by the above package) and add the following to the RegisterServices method
kernel.Bind<MyContext>().ToSelf().InRequestScope(); //binding in the context in request scope, this will let us use it in our controllers
Inside the controller, the context is used as follows
public class MyController : ....{ private readonly MyContext _context; public MyController(MyContext context){ _context = context; }
This is a very simple example for you to try, there are many better ways to structure this when your application grows (like ninject modules), but it will show how DI works.
A few notes: always make sure you bind the context in the requestcope (or more often), since DBContext has the unpleasant habit of growing pretty fast if it lasts too long.
In terms of sharing this with your external things that can also be introduced, for example
public class MyExternalLogic{ public MyExternalLogic(MyContext context){....} } public class MyController : ....{ private readonly MyContext _context; public MyController(MyContext context, MyExternalLogic logic){ _context = context; ...}
In the above example, the same DbContext instance will be used for both MyController and MyExternalLogic. Ninject will handle the creation of both objects.
There are also many other DI containers that will give you a very similar experience. I highly recommend DI as it helps a lot when using unit test.
A few more examples of how I use Ninject to structure my MVC applications, look at some of my projects on github, such as https://github.com/lukemcgregor/StaticVoid.Blog