How to handle different responsibilities while using only one instance of DbContext?

If all of your models are based on entities in the same database, there is not reason not to use a single context instance to manage them within the same controller. I would go with the simple solution and use a single context instance.

Based on the answer here stackoverflow. Com/questions/5187562/… I cannot use a singleton context – csharpsi Nov 4 at 15:37 Based on the comments in the OP, my comment above is invalid. – csharpsi Nov 4 at 15:55.

If you're using the Repository pattern then you have at least a class which implements one of more repository interfaces. Since your code is coupled to an interface and not to an implementation you don't have to worry. However, you should treat the repository implementation as a singleton i.

E every method should be independent and the class should not store state (you can store the conenction string since is basically a constant). So a method look like this public void Save(Entity entity) { using(var db=new MyDbContext()) { //do stuff } } This way you're always disposing the data context and thus there should be no memory leaks As for SRP, the role of an repository is to get/save objects. If it does that it's good.

With this approach, in the edit method I would use one instance of the context to get the item to update and a separate instance to save it, which would not work. – csharpsi Nov 4 at 15:36.

The problem potentially with a single instance is not releasing the context when it is done. If you use dependency injection, this will handle the disposing of this object when it is done. I do not recommend the design you have above either - you are giving your ViewModel data access behavior, which generally they aren't purposed for.

A ViewModel has properties for the model and MAYBE some functionality specific to prepare that data. Inject a service layer into your controller whose responsibility it is to populate that viewmodel OR return a model. You can then just use automapper to map that model to your ViewModel.

There's a neat attribute available as well to do this mapping. Check out: lostechies.com/jimmybogard/2009/06/30/ho....

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions