I'm refactoring and redesigning the domain objects of my application which uses MVVM to some extent. Is there anything that speaks against making all Domain objects (POCOs) inherit from INotifyPropertyChanged, so anyone can observe the objects as they wish.
In combination with https://stackoverflow.com/a/1316566/448357 this does not even have to be very ugly.
On the other hand, what about polluting my domain object with stuff that might not be required at all, because there will be a separate View-Model anyway? Margabit points out: UI Model != Domain Model
IMO, Domain objects shouldn't implement INotifyPropertyChanged. The one who should be implementing it is your ViewModel.
The reasons for that is:
You would probably mostly need to raise a PropertyChanged event inside your viewmodel which holds your POCOs
You would be implementing it only once.
If your POCO wants to raise an event and notify that something has occured inside it, im not sure PropertyChanged would be the most meaningful event to raise.
I think it depends a little bit on the scope of the project: if this is a small project, where Domainmodels are also used as UI-mmodels, sure go ahed an do so if you like.
But if you frequently NEED UI-models, e.g. because there are a lot of properties / methods which are not part of your domain model, don't bother - you create overhead for little or no reason.
When do you need a UI-model? My rule of thumb: If you are introducing a property with an[NotMapped] (Entity Framework) Attribute, go ahead and make a UI-model with this property.
Alsoif there is a chance that parts of this project are used in another context( Webapp, phone etc. pp) , I would advise against it- you will need UI models anyway.
To avoid to insert code in your classes you can make a transparent proxy.
You can use Castle
http://www.castleproject.org/dynamicproxy/index.html
The only limitation is that you have to create instances of your classes via factory.
You could also use System.Runtime.Remoting.Proxies.RealProxy class but your base class must derive from MarshalByRef (is still POCO? :) ).
http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=IT-IT&k=k(SYSTEM.RUNTIME.REMOTING.PROXIES.REALPROXY)%3bk(TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV4.0%22)%3bk(DevLang-CSHARP)&rd=true
Related
Almost every MVVM example I've come across has both the Model and ViewModel implementing INotifyPropertyChanged.
Other sources (ones which focus on domain modeling) seem to suggest that Models should be incredibly plain (something to do with separation of concerns?) with essentially no references to anything. Unfortunately, those sources don't use MVVM.
I'm trying to reconcile the two.
-I'm relatively new to programming and completely new to design patterns and the like so please try to go easy on me.
Edit: Let me rephrase my question. Given that the answer to the above seems to be "sometimes one and sometimes the other," WHEN should you do one and and when should you do the other. Also, how would each be implemented?
(That isn't answered in the other post. It just has them arguing with each other).
Models have to implement INotifyPropertyChanged to inform the view model that they have changed. If the model doesn't implement INotifyPropertyChanged (or another equivalent interface), then the view model is stuck using polling or other similarly inefficient methods to detect changes in the model state.
This MSDN page may be useful reading to further understand the roles of the various components that make up the MVVM pattern.
I have no idea if this is a best practice, but I have my ViewModel set up so that it is the only active entity. The Model is only directly changed when created by reading from a database (and then loaded into a ViewModel), or before saving to database (extracting from ViewModel, modifying Model properties that only matter to the database, like foreign keys).
If for some reason you desire being able to have multiple ViewModels connected to the same Model or have a need to change a Model from under a ViewModel, then you'd have a good reason to implement INotifyPropertyChanged on the Model.
I'm a relative amateur, so take what I say with a grain of salt. But this is what I've been gathering, and enforcing this separation has, I think, made my code cleaner and easier to understand and debug. So for my own projects, I'm going to try avoiding implementing INotifyPropertyChanged on my Models if I can avoid it.
My question is fairly simple and already asked in the title.
Here's the context: I've got a domain with entities and repositories. The result of a query is mapped into DTO and sent to the GUI.
The GUI is implemented with WPF and for the mapping, I need classes that implement INotifyPropertyChanged.
My first idea is to have DTO that implement this interface because I foresee a lot of work to map again my DTO into items that implement INotifyPropertyChanged.
Is it a good practice? Has it pitfalls I haven't seen? What is the "official" good practice for this situation?
DTOs are supposed to be very simple, lightweight, data transfer objects. Because of this, I wouldn't implement anything on them other than their data. Also, I believe if serializing the class to/from a WCF server, the properties need to all be public, so you can't make things like the Id read-only
I would create Model classes that implement INotifyPropertyChanged and IDataErrorInfo for property changed notification and validation purposes, and have them accept a DTO in the Constructor. Using something like AutoMapper will make mapping a DTO to a Model pretty simple
Even though it is a DTO, there isn't much reason to not implement INPC.
INPC is in every .net impl that I can think of, so you aren't taking extra dependencies that you might want to avoid at both ends of a connection (usually why you would use a DTO)
Using NotifyPropertyWeaver you can do it with very little code.
Just because your DTO implements that interface, I don't think it makes it any less of a DTO.
The wikipedia definition of DTO says that there is no behavior in a DTO. You have now added behavior in the form of the PropertyChanged event, but given that the whole reason to use a DTO is for remote objects (http://msdn.microsoft.com/en-us/library/ms978717.aspx) I am still convinced it is OK.
Fowler states that the point of a DTO is to reduce the number of parameters in a remote call. (http://martinfowler.com/eaaCatalog/dataTransferObject.html) This doesn't even say that you can't add behavior.
INPC away!
The best practice with WPF would be to use the MVVM pattern (Model-View-ViewModel).
In this instance, your DTO is the Model. You should not pass the Model directly to the View but instead wrap it into a ViewModel that can in turn implement the notification mechanisms.
This way the Model is pure data and doesn't need to worry about what is using it.
Also, there are several frameworks you can use to simplify the mapping work (e.g. Automapper).
I have one ViewModel for enums handling (few entities in Entity Framework).
1) Philosophically, is it a good practice to use a SINGLETON PATTERN for this ViewModel, because it's widespread over all application and it's used on many places.
2) Isn't it a problem for ViewModel (and associated ObjectContext) to live for very long time?
Thank you!
This should probably be broken up into two separate questions, but I'll take a stab at both:
No. There's no reason a ViewModel should be a Singleton. You actually WANT multiple instances (since each is going to vary) rather than a single instance that lives for the run of the application. Just because an object is widespread and is used frequently doesn't make it a good candidate for a singleton...it just means that it's a good object.
ViewModels should not have a very long lifetime (another reason you don't want a singleton). In MVVM, the lifespan of a given ViewModel would be as long as the user has the window open and finishes their changes.
Having a singleton ViewModel is entirely valid in specific cases. One example I have used multiple times is a SettingsViewModel. Which needs to be accessed globally by multiple systems within the app. My Settings Model on creation loads up settings from a file, the ViewModel allows me to bind to modify those settings. The singleton allows me to globally access those settings where I need instead of passing them around as parameters.
Entirely valid, in this case.
1) don't do it. see MVVM ViewModels Singleton
2) I don't think it's a good idea to have a viewmodel coupled to an object context. It should be just a viewmodel, providing data to a view; but not tightly coupled to any data persistance technology. Instead, inject services that take care of this, so you can mock them.
The objects only live on the stack as long as the garbage collectors deems them to be necessary. Philosophically no it is not a good idea to use Singleton as it breaks encapsulation. See article: Singleton antipattern
As Justin mentioned, it seems unlikely you'll need your ViewModels to follow the Singleton Pattern. However, as you mentioned, View Models are used throughout the system. Consider pulling common functionality into base classes (if you like inheritance) and/or pull reusable components into objects to take advantage of composition.
An easy way to start this is all the lines of Josh Smith's ViewModelBase and a typical ViewModel's usage of INotifyPropertyChanged.
Give that code a look here: http://mvvmfoundation.codeplex.com/
I've been reading too much probably and am suffering from some information overload. So I would appreciate some explicit guidance.
From what I've gathered, I can use VS2010's T4 template thingy to generate POCO classes that aren't tied directly to the EF. I would place these in their own project while my DAL would have an ObjectContext-derived class, right?
Once I have these classes, is it acceptable practice to use them in the UI layer? That is, say one of the generated classes is BookInfo that holds stuff about books for a public library (Title, edition, pages, summary etc.).
My BLL would contain a class BooksBLL for example like so:
public class BooksBLL
{
ObjectContext _context;
public void AddBook(BookInfo book) { ... }
public void DeleteBook(int bookID) { ... }
public void UpdateBook(int bookID, BookInfo newBook) { ... }
//Advanced search taking possibly all fields into consideration
public List<BookInfo> ResolveSearch(Func<BookInfo, bool> filter) { ... }
//etc...
}
So, my ViewModels in my MVVM UI app will be communicating with the above BLL class and exchanging BookInfo instances. Is that okay?
Furthermore, MVVM posts on the Web suggest implementing IDataErrorInfo for validation purposes. Is it okay if I implement said interface on the generated POCO class? I see from samples that those generated POCO classes contain all virtual properties and stuf and I hope adding my own logic would be okay?
If it makes any difference, at present, my app does not use WCF (or any networking stuff).
Also, if you see something terribly wrong with the way I'm trying to build my BLL, please feel free to offer help in that area too.
Update (Additional info as requested):
I'm trying to create a library automation application. It is not network based at present.
I am thinking about having layers as follows:
A project consisting of generated POCO classes (BookInfo, Author, Member, Publisher, Contact etc.)
A project with the ObjectContext-derived class (DAL?)
A Business Logic Layer with classes like the one I mentioned above (BooksBLL, AuthorsBLL etc)
A WPF UI layer using the MVVM pattern. (Hence my sub-question about IDataErrorInfo implementation).
So I'm wondering about stuff like using an instance of BooksBLL in a ViewModel class, calling ResolveSearch() on it to obtain a List<BookInfo> and presenting it... that is, using the POCO classes everywhere.
Or should I have additional classes that mirror the POCO classes exposed from my BLL?
If any more detail is needed, please ask.
What you're doing is basically the Repository pattern, for which Entity Framework and POCO are a great fit.
So, my ViewModels in my MVVM UI app will be communicating with the above BLL class and exchanging BookInfo instances. Is that okay?
That's exactly what POCO objects are for; there's no difference between the classes that are generated and how you would write them by hand. It's your ObjectContext that encapsulates all the logic around persisting any changes back to the database, and that's not directly exposed to your UI.
I'm not personally familiar with IDataErrorInfo but if right now your entities will only be used in this single app, I don't see any reason not to put it directly in the generated classes. Adding it to the T4 template would be ideal if that's possible, it would save you having to code it by hand for every class if the error messages follow any logical pattern.
Also, if you see something terribly wrong with the way I'm trying to build my BLL, please feel free to offer help in that area too.
This isn't terribly wrong by any means, but if you plan to write unit tests against your BLL (which I would recommend), you will want to change your ObjectContext member to IObjectContext. That way you can substitute any class implementing the IObjectContext interface at runtime (such as your actual ObjectContext), which will allow you to do testing against an in-memory (i.e. mocked) context and not have to hit the database.
Similarly, think about replacing your List<BookInfo> with an interface of some kind such as IList<BookInfo> or IBindingList<BookInfo> or the lowest common denominator IEnumerable<BookInfo>. That way you're not tied directly to the specific class List<T> and if your needs change over time, which tends to happen, it will reduce the refactoring necessary to replace your List<BookInfo> with something else, assuming whatever you're replacing it with implements the interface you've chosen.
You don't need to do anything in particular... as Mark said, there is no "right" answer. However, if your application is simple enough that you would simply be duplicating your classes (e.g. BookInfoUI & BookInfoBLL), then I'd recommend just using the business classes. The extra layer wouldn't serve a purpose, and so it shouldn't exist. Eric Evans in DDD even recommends putting all your logic in the UI layer if you app is simple and has very little business logic.
To make the distinction, the application layer should have classes that model what happens within the application, and the domain layer should have classes that model what happens in the domain. For example, if you have a search page, your UI layer might retrieve a list of BookSearchResult objects from a BookSearchService in the application layer, which would use the domain to pull a list of BookInfo.
Answers to your questions may depend on the size and complexity of your application. So I am afraid there will be valid arguments to answer your questions with Yes and No as well.
Personally I will answer your two main questions both with Yes:
Is it acceptable practice to use POCO (Domain) classes in the UI layer?
I guess with "UI layer" you don't actually mean the View part of the MVVM pattern but the ViewModels. (Most MVVM specialists would argue against letting a View directly reference the Model at all, I believe.)
It is not unusual to wrap a POCO from your Domain project as a property into a ViewModel and to bind this wrapped POCO directly to the View. The big Pro is: It's easy. You don't need additional ViewModel classes or replicated properties in a ViewModel and then copy those properties between the objects.
However, if you are using WPF you must take into account that the binding engine will directly write into your POCO properties if you bind them to a View. This might not always be what you want, especially if you are working with attached and change-tracked entities in a WPF form. You have to think about cancellation scenarios or how you restore properties after a cancellation which have been changed by the binding engine.
In my current project I am working with detached entities: I load the POCO from the data layer, detach it from context, dispose the context and then work with that copy in the ViewModel and bind it to the View. Updating in the data layer happens by creating a new context, loading the original entity from the DB by ID and then updating the properties from the changed POCO which was bound to the View. So the problem of unwished changes of an attached entity disappears with this approach. But there are also downsides to work with detached entites (updating is more complex for instance).
Is it okay if I implement the IDataErrorInfo interface on the generated POCO class?
If you bind your POCO entities to a View (through a wrapping ViewModel) it is not only OK but you even must implement IDataErrorInfo on the POCO class if you want to leverage the built-in property validation of the WPF binding engine. Although this interface is mainly used together with UI technologies it is part of System.ComponentModel namespace and therefore not directly tied to any UI namespaces. Basically IDataErrorInfo is only a simple contract which supports reporting of the object's state which also might be useful outside of a UI context.
The same is true for the INotifyPropertyChanged interface which you also would need to implement on your POCO classes if you bind them directly to a View.
I often see opinions which would disagree with me for several architectural reasons. But none of those opinions argue that another approach is easier. If you strictly would want to avoid to have POCO model classes in your ViewModel layer, you need to add another mapping layer with additional complexity and programming and maintenance effort. So I would vote: Keep it simple as long as you do not have a convincing reason and clear benefit to make your architecture more complex.
After fighting for a while with maintaining model-viewmodel relationships (eg. creating vm instances for each instance of model) I've got some ideas that might be quite controversial, but I'm curious of opinions.
What if VM class was made to maintain a static list of containers for model instances.
Those could(or even should) be weak references so whenever model class instance is out of scope its viewmodel is automatically disposed. Another option would be to reuse vm instances.
Another idea that would work well with the first one might be creating an implicit cast operator from model to viewmodel class. I would always get the same instance of vm whenever casting from model instance.
What do you think about it ? Is this a hard violation of rules and MVVM pattern?
//edit
I should probably provide also what was the motive behind this: in my app I have multiple places where I use one of my model classes and need corresponding vm references. In every such place I need to observe a collection and react to changes -creating or removing vm instances. This is basically the same code that is repeated in many places => I thought of creating only one place to do that (implicit cast is just a candy it's not required to solve the real problem). Or maybe instead of static lists I should create a manager that would handle view model instance creation for all my classes?
First of all, I am not to sure whether your ideas violate the MVVM pattern. In my opinion it is not that important to fullfill patterns in every case. A pattern in my eyes suggests strategies to solve problems. In most cases it is not worth following a pattern 100% by all means. If there is a pragmatic solution you should rather use this one. Of course this should be solutions that lead you to your aims, e.g. unit testable, separation of UI and applicatiopn logic and so on.
Anyway, when I was reading your article the first time I thought implementing a cast operator is good idea. But if I am not wrong, you need to reference the view model in your model. I always try to avoid that to maximize re-use opportunities. But I think having such a reference does not violate the pattern. Maybe someone else can tell more about that.
For me your manager idea is the best way. I use a similar way to create view models. It depends on how many view model you need to create, but you should rather create new view models than re-using existing ones. Somewhere I read that view models should be some kind of state machine to the view. Following this idea, you never know in what state the view model is when you re-use it. So the preferred way is to create a new view model.
Just some thoughts! Maybe there are some other ideas...