newbie here, sorry if this is an obvious question, and sorry for my English. I tried to Google but didn't find an answer to my question.
I'm using Visual Studio, Autofac, EF CTP5 code only (maybe later will switch to HHibernate due to EF CTP5 does not support IoC container), and trying to use the following patterns: MVVM, DI, DDD.
My question is: When multiple ViewModels request the same domain-object from the repository, should I give them the same instance or create a new instance for each request?
If I create a new instance for each request, I guess I would write something like this:
public class PersonRepository
{
public Person GetById(int id)
{
using (var dbContext = new MainDbContext())
{
return dbContext.Persons.Where(x => x.Id == id);
}
}
}
And after any ViewModle modifies its instance of the domain-object, I would have to find a way to notify all other ViweModels to update their instances, to ensure data integrity.
If I give the same instance of the domain-object for all requests, then I guess I would have to write something like this:
public class PersonRepository
{
List<Person> _cache = new List<Person>();
public Person GetById(int id)
{
var person = getFromCache(id);
if (person == null)
{
person = getFromDatabase(id);
_cache.Add(person);
}
return person;
}
}
And I also need to find a way to remove instances from the cache when they are not needed by any ViewModels (or use weakreference for the cache), to avoid memory leak.
Which way should I go? Do I have better options?
Thanks!
Edit: Changed contents for better description.
(sorry for my English)
Update:
After I did some research on this, I realized this question is too confusing, so I posted a new question at here: Multiple ViewModels modify the same domain object