I would suggest you use a Dependency Injection framework. You can register your DbContext
as per request
container.RegisterType<MyDbContext>().InstancePerHttpRequest();
And inject it as a constructor parameter to the controller.
public class MyController : Controller
{
public MyController(MyDbContext myDbContext)
{
_myDbContext = myDbContext;
}
}
If the registered type implements IDisposable
then the DI framework will dispose it when the request ends.
1st approach: It is much more cleaner to use ID framework than manually implementing it. Further all your requests may not need your UoW.
2nd approach: The controller should not know how to construct your UoW(DbContext). Purpose is not reduce the coupling between components.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…