in a typical MVC3 app with an EF model, each controller instantiates its own copy of the model container. this means that if I were to create a class in a different file and it needed access to the model, it would need to instantiate its own container.
Consider the following:
namespace X.Web.Controllers
{
public class TestController : Controller
{
EFContainer db = new EFContainer();
public ActionResult Whatever()
{
User u = db.Users.Find(3);
...
}
if I wanted to abstract my fetching of a user in a class Auth then it would have to instantiate its own db since it doesn’t have access to the controller’s — all fine until the controller wants to make changes to the returned object:
public ActionResult Whatever()
{
User u = Auth.GetUser();
u.Name = "ekkis";
db.SaveChanges();
...
}
since the user at that point belongs to a different context… so either I have to share my db with Auth or perhaps I’d have to do a moronic double-lookup:
public ActionResult Whatever()
{
int id = Auth.GetUserId();
User u = db.Users.Find(id);
u.Name = "ekkis";
db.SaveChanges();
...
}
what is the recommended way of dealing with this?
Why don’t you pass in your model / EF context via constructor injection into your
Authclass? That seems to be the most reasonable way (same applies to your controller actually once you have an IOC container set up).Ideally you would also make this work based on an abstract interface so you can test
Authindependently of EF.