Sharing Data between Silverlight ViewModels - silverlight-3.0

I have a complex User Control that contains some views, each have its own ViewModel.
My question is how can all of these ViewModels share some data (for example an observable collection) without each one have a separate call to the service?

The service should be an abstraction of the data. Whether that data is pulled from a WS, DB, etc...should be irrelevant. Each ViewModel can contain a property which will be bound to by the View. That property can be an ObservableCollection<T> which wraps a call to the service. That data may in fact be cached via the service and only update periodically but either way it will push the data to a single point of reference for retrieval amongst the ViewModels.

Related

Application design using DDD

I am designing solution strucure for an application. I am planning to use Domain driven design. Asp.net MVC and Entity framework. Need your inputs in some areas.
Data Access is designed using Entity framework code first
Reposirotires are built on top of EF Data Acces
Domain model is designed usind domain model on top of Repositories
Application serveices are built on top of Damain layer
UI is developed on top of Application services
The flow is
UI (controller) --> Application service --> Domain Layer --> Repositories --> Data Access --> Data base.
I am not very clear of how to share the data in between the layers.
My Domain model can be used to sahre data between Repositories, Data Access and Domain Layer. I am just thinking the way the data should be passed from Daomin Layert to Application Service and Application Service to UI. I can use DTOs, But not sure weather it is a good option or not, as i have some models are already in Domain Model, View model in UI.
Reuse Domain Model or UI Model is not good, it will make your layers are tightly coupled. It's very difficult to develop large scale applications that way.
What you think is correct, Application is a thin layer, it's just a bunch of Actions which will be called directly from UI layer and information will be passed through an object called ActionParameter. ActionParameters are defined in Application layer and ActionParameter objects are constructed on UI layer and passed to Application layer.
Application will retrieve data from DB via Data Access Layer. An Query Action sometimes need to fetch data from many source, different domain entities and data need to be projected, transformed or formatted before return to UI layer. We will have something like ActionResult objects that contains all data to be returned to UI layer.
It seems there will be a lot of codes but I think it's necessary. Each layer has its own purpose and when we change one, other layers won't be impacted.
Given the flow you describe, create view models in the UI layer to be instantiated by the controller. A view model is simple object to which the view binds. This should be decoupled from the underlying domain model to address concerns noted by namkha87.
As far as the data access layer, you can use the domain objects themselves for object-relational mapping since EF allows this. There is no need for an intermediate DTO here.
Another thing to consider is separating the model used for queries from one's used to invoke behavior. This way, you can ensure that an application service never exposes behavioral domain objects, only read-models. The problem with having an application service expose domain objects to outer layers is that it will allow those outer layers to invoke behaviors on those objects the results being undefined. When you only return read-only objects with no behaviors, this isn't a problem. For data coming back, don't have the UI layer created domain objects directly - you should distinguish between entities and simple data.

Do viewModels belong in the Web Layer or Service Layer?

My application currently follows a service pattern, where the models are thin and mvc-blind, and the controllers call Services that retrieve data from the model.
Right now my controllers construct and consume ViewModels based on the data that they get from the Services or Client.
What I'm wondering is - would it be wise to relocate the ViewModel classes to the service layer?
Before:
Controller asks service for data
Controller accepts data and constructs viewModel
Controller sends viewModel to client
Client sends data back to Controller
Controller takes data from viewModel and sends it back to Service to update db
After
Controller asks service for data
Service constructs a viewModel and populates it with data
Controller accepts viewModel
Controller sends viewModel to client
Client sends data back to Controller
Controller forwards viewModel to Service
Service pulls data apart and performs updates/queries as needed
Is one better than the other? Why?
Before is the better approach. Your view model should be a model of your view, as the name implies.
It may contain data retrieved by a service, but it's likely to also be augmented with additional data required for that specific view.
Also, the view model is likely to be UI technology specific, whereas the service should be completely UI agnostic. The service code is likely to be reusable across UI technologies, but the view model code is likely not to be.
In fact in a fat client application, your view models are likely to be more than just data transfer objects, but will also contain presentation logic as well as manage user state etc. Your service code will most likely not be tied to a specific client implementation.

Should a service layer return view models for an MVC application?

Say you have an ASP.NET MVC project and are using a service layer, such as in this contact manager tutorial on the asp.net site: http://www.asp.net/mvc/tutorials/iteration-4-make-the-application-loosely-coupled-cs
If you have viewmodels for your views, is the service layer the appropriate place to provide each viewmodel? For instance, in the service layer code sample there is a method
public IEnumerable<Contact> ListContacts()
{
return _repository.ListContacts();
}
If instead you wanted a IEnumerable, should it go in the service layer, or is there somewhere else that is the "correct" place?
Perhaps more appropriately, if you have a separate viewmodel for each view associated with ContactController, should ContactManagerService have a separate method to return each viewmodel? If the service layer is not the proper place, where should viewmodel objects be initialized for use by the controller?
Generally, no.
View models are intended to provide information to and from views and should be specific to the application, as opposed to the general domain. Controllers should orchestrate interaction with repositories, services (I am making some assumptions of the definition of service here), etc and handle building and validating view models, and also contain the logic of determining views to render.
By leaking view models into a "service" layer, you are blurring your layers and now have possible application and presentation specific mixed in with what should focused with domain-level responsibilities.
No, I don't think so. Services should care only about the problem domain, not the view that renders results. Return values should be expressed in terms of domain objects, not views.
As per the traditional approach or theory wise, ViewModel should be part of User interface layer. At least the name says so.
But when you get down to implementing it yourself with Entity Framework, MVC, Repository etc, then you realise something else.
Someone has to map Entity/DB Models with ViewModels(DTO mentioned in the end). Should this be done in [A] the UI layer (by the Controller), or in [B] the Service layer?
I go with Option B. Option A is a no no because of the simple fact that several entity models combine together to form a ViewModel. We may not pass unnecessary data to UI layer, whereas in option B, the service can play with data and pass only the required/minimum to the UI layer after mapping (to the ViewModel).
But still, let us go with option A, put ViewModel in the UI layer(and entity model in Service layer).
If the Service layer needs to map to the ViewModel, then the Service layer need to access ViewModel in UI layer. Which library/project? The Viewmodel should be in a separate project in the UI layer, and this project needs to be referenced by Service Layer. If the ViewModel is not in a separate project, then there is circular reference, so no go. It looks awkward to have Service layer accessing UI layer but still we could cope with it.
But what if there is another UI app using this service? What if there is a mobile app? How different can the ViewModel be? Should the Service access the same view model project? Will all UI projects access the same ViewModel project or they have their own?
After these considerations my answer would be to put the Viewmodel project in Service Layer. Every UI layer has to access the Service layer anyways! And there could be a lot of similar ViewModels that they all could use (hence mapping becomes easier for service layer). Mappings are done through linq these days, which is another plus.
Lastly, there is this discussion about DTO. And also about data annotation in ViewModels. ViewModels with data annotations(Microsoft.Web.Mvc.DataAnnotations.dll) cannot reside in service layer instead they reside in UI layer(but ComponentModel.DataAnnotations.dll can reside in service layer). If all projects are in one solution(.sln), then it doesn't matter which layer you put it. In enterprise applications, each layer will have its own solution.
So DTO actually is a ViewModel because mostly there will be one on one mapping between the two(say with AutoMapper). Again DTO still has the logic needed for the UI(or multiple applications) and resides in Service Layer. And the UI layer ViewModel(if we use Microsoft.Web.Mvc.DataAnnotations.dll) is just to copy the data from DTO, with some 'behavior'/attributes added to it.
[Now this discussion is about to take an interesting turn read on...:I]
And don't think data-annotation attributes are just for UI. If you limit the validation using System.ComponentModel.DataAnnotations.dll
then the same ViewModel can also be used for front-end & backend validation(thus removing UI-residing-ViewModel-copy-of-DTO). Moreover attributes can also be used in entity models. Eg: using .tt, Entity Framework data models can be autogenerated with validation attributes to do some DB validations like max-length before sending to the back end. This saves round-trips from UI to backend for validation. It also enables back-end to re-validate for security reasons. So a model is a self-reliant validator and you can pass it around easily. Another advantage is that if backend validation changes in DB then .tt (reads DB specifics and create the attribute for entity class) will automatically pick that up. This can force UI validation unit tests to fail as well, which is a big plus(so we can correct it and inform all UIs/consumers instead of accidentally forgetting and failing). Yes, the discussion is moving towards a good framework design. As you can see it is all related: tier-wise validation, unit test strategy, caching strategy, etc.
Although not directly related to the question. 'ViewModel Façade' mentioned in this must watch channel 9 link is also worth exploring. It starts exactly at 11 minutes 49 seconds in the video. Because this would be the next step/thought once your current question given above is sorted out: 'How to organize ViewModels?'
And Lastly, many of these model vs logic issues could be resolved with REST. Because every client can have the intelligence to query the data and get only the data that it needs. And it keeps the model in UI, there is no server/service layer model/logic. The only duplication then will be on the automated tests that each client need to perform. Also if there are changes in data then some clients fail if they do not adapt to the change. The question then is, are you removing service layer altogether(and the models they carry) or pushing the service layer up to your UI project(so model issue still persists) which calls the REST API. But in terms of the responsibility of Service layer, they are the same regardless.
Also in your example "_repository.ListContacts()" is returning a ViewModel from repository. This is not a mature way. Repositories should provide entity models or DB models. This gets converted to view models and it is this view model that is returned by the service layer.
This has come a bit of an "it depends" where I work - we have generally had a controller consuming some service(s) - then combining returned DTO's into a 'ViewModel' that would then get passed to the client - either via JSON result, or bound in the Razor Template.
Thing is, about 80% of the time - the mapping of DTO to ViewModel has been 1-1. We are starting to move towards 'Where needed, just consume the DTO directly, but when the DTO and what we need in our client/view don't match up - then we create a ViewModel and do the mapping between objects as needed'.
Although I'm still not convinced that this is the best or right solution - as it ends up leading to some heated discussions of 'are we just adding X to the DTO to meet the needs of the view?'
I suppose that depends on what you consider the "services" to be. I've never really liked the term service in the context of a single class; it's incredibly vague and doesn't tell you much about the actual purpose of the class.
If the "service layer" is a physical layer, such as a web service, then absolutely not; services in an SOA context should expose domain/business operations, not data and not presentation logic. But if service is just being used as an abstract concept for a further level of encapsulation, I don't see any problem with using it the way you desribe.
Just don't mix concepts. If your service deals with view models then it should be a presentation service and be layered over top of the actual Model, never directly touching the database or any business logic.
Hi I see very good answers here.
And for myself I do an other aproach.
I have to kinds of models , one is viewmodel and the other is shared models. The viewmodels stays on the UI layer and the shared models stays on a separate project.
The shared models can theoretically be used anyware because those are standalone.
This models provides some abstraction if you want to return specific data from your service layer or if you need something specific from your repository.
I don't really know if this is a good aproach but it works so well on my projects. For example
When I need to provide some information to create new objects to the database i can use the shared models directly to the service layer it saves me some complexity.
The shared models needs to be mapped sometimes , but you can ensure that your service is not leaking inesssary data to the UI.
You can see shared models as an extension but not to build your UI logic with it, you should have viewmodels to do that.
You can combine viewmodels with this shared models to save you time you can use inheritance.
The shared models has to be neutral and should not have any kind of logic.

what is the difference between a view model and a data transfer object?

I'm basing this question on Fowler PoEAA. Given your familiarity with this text, aren't the ViewModels used in ASP.NET MVC the same as DTOs? Why or why not? Thank you.
They serve a similar purpose (encapsulating data for another layer of the application) but they do it differently and for different reasons.
The purpose of a DTO is to reduce the number of calls between tiers of an application, especially when those calls are expensive (e.g. distributed systems). DTOs are almost always trivially serializable, and almost never contain any behaviour.
For example, you're developing an e-Commerce site. CreateCustomer and AddCustomerAddress are separate operations at the database level, but you might for performance reasons want to aggregate their data into a NewCustomerWithAddressDto so that your client only needs to make one round-trip to the server, and doesn't need to care that the server might be doing a bunch of different things with the parcel of data.
The term "ViewModel" means slightly different things in different flavours of MV*, but its purpose is mainly separation of concerns. Your Model is frequently optimised for some purpose other than presentation, and it's the responsibility of the ViewModel to decouple your View from the Model's implementation details. Additionally, most MV* patterns advise making your Views as "dumb" as possible, and so the ViewModel sometimes takes responsibility for presentation logic.
For example, in the same e-Commerce application, your CustomerModel is the wrong "shape" for presentation on your "New Customer" View. For starters, your View has two form fields for your user to enter and confirm their password, and your CustomerModel doesn't contain a password field at all! Your NewCustomerViewModel will contain those fields and might, depending on your flavour of MV*, be responsible for some presentation logic (e.g. to show/hide parts of the view) and basic validation (e.g. ensuring that both password fields match).
The purpose is different:
DTO's are used to transfer data
ViewModels are used to show data to an end user.
So normally ViewModels contain the presentation data, witch is in a lot of cases similar to what is in a DTO, but with some differences. Think of representation of enums, localization, currency, date formats, ... . This is because normally there should be no logic in your view.
DTOs in MVVM and MVP are usually Very Dumb Objects and are basically just a bunch of property setters and getters. ViewModels on the other hand can have some behaviour.
A practical positive side effect of having DTOs is allow easier serialization. If you have a rather complex object in, say C#, you will often find yourself having to selectively turn things off that you don't want serialized. This can get rather ugly and DTOs simplify this process.
A View Model and a Data Transfer object has similarities and differences.
Similar:
Transfer data in a record (object instance, perhaps serialized) to a receiver, whether a view or a service
Difference:
A View Model is intended to be sent to a View, where it will be displayed, with formatting.
A View Model also sends back data to a controller.
A DTO is usually not intended for presentation. It is intended to send raw data.
Both serve the same purpose to model data coming to and from the backend.
View Models model data hitting the backend from a front end visual system (forms, user inputs, etc) and vice versa model data to be sent to the front end for the same purpose to fulfill some visual requirement.
Data Transfer Objects model data hitting the backend from some client system (background api's, data that still needs to be worked on, a clients background services, etc) and vice versa model data to be sent to the client system. Even though the client system may have visual elements, the DTO call itself is used for a non visual use case.
The technical differences between the two arise from the semantic and contextual meaning of the two as mentioned above, such as view models possibly having more behaviour.
I always thought DTO's were supposed to be almost like for like your Entities and ViewModels were containers for those DTO's when presenting to the View.
In that instance you would create 'pseudo' DTO's that combine 2 or more other DTO's together to pass data in one 'model' to a method or API etc.
I never came up with a naming convention for those 'pseudo' DTO's though, so just ended up suffixing them with "DTO", but put them in the models Folder along with the view models 🤷‍♂️
The ViewModel may have presentation logic based on; the current user's permissions, the display type, the data in the DTO's etc.
I've always tried to keep my views as 'dumb' as possible with as little as possible code in them, and just bound the view to the properties in the view model.

In MVC, what are the limitations on the Controller?

Should the Controller make direct assignments on the Model objects, or just tell the Model what needs to be done?
The controller has two traditional roles:
handling the input event from the UI (registered handler or callback)
notifying the model of an action--which may or may not result in a change on the model's state
It does not perform data validation, that is on the model, nor does it have any say in how information is presented.
It depends largely on the scope of your application. If it's relatively quick and dirty, then there's no sense in over-engineering, and sure, your controllers can talk to your model objects. On the other hand, if it needs to be more "enterprisey" for whatever reason, a good pattern to use in conjunction with MVC is the so-called "Business Delegate". This is where you can compose coarse-grained methods out of one or more methods on one or more model objects; for instance deleting an object and then returning a refreshed list without that object. This layer gives two advantages. For one, it decouples the controllers from whatever ORM system is being used for model objects. Furthermore, it is the layer that finally must constructively deal with any exceptions that may have occurred instead of re-throwing them.
I don't think a controller should be dealing with model objects.
I tend to think that controller is really part of the UI tier. I prefer to inject a service layer in-between the controller and the rest of the app. The web tier accepts HTTP requests, unmarshals parameters from request objects into objects that the service interface can deal with, and marshals the response to send back. All the work with transactions, units of work, and dealing with model and persistence objects is done by the service.
This approach is more service oriented. It separates the service from the user interface, leaving open the possibility that several clients can reuse the same service. It makes the layer that marshals requests to the service "thin", so it's easy to switch out SOAP services for REST or EJB or CORBA or whatever the next new thing will be.
The Model services don't have to know the existence of the controller, thus, controller can do the stuff what ever the view needs by utilising the model services.

Resources