I am new to this whole design concept, and in reading for the last few weeks I have gathered a lot of information, but it seems scattered and conflicted. Terms are mixed, and I am just having a hard time wrapping my mind around this.
The pattern I am using is like this and assume the flow as follows:
MVC Application
The controller(s) process the request/response from the client for a given view. Inside the controllers action methods, they contact the services (Service Layer) and either request objects to build the view models, and sen the objects from the view models back.
View Models
I am using strongly typed view models to and from the views.
Are view models DTO's? Should they contain just simple properties like Name, AddressLine1, Address City, etc, or should they contain complex properties, multiple objects, etc.
Is the validation in the view model. If so would it be validation like required fields, field length, etc. Then validation like user name already exists, or where you would need to interact with other objects in the service layer?
Can the view models just contain the POCO classes returned from EF, or should I be using the AutoMapper?
If using AutoMapper and DTO, are DTO's clones of the POCO classes?
Would you map in the controller, view model, or in the service layer below?
Services
To me, the service(s) are objects that contact the repository(s) to get POCO objects back from the EF. This is where all of my business logic is. Once the service hands an object back to a repository to be persisted to the EF, they are considered valid objects. Is this correct?
Repositories
There is no business logic in them, they are just used to transport objects between the service(s) and the EF. Is this correct? I am implementing Interfaces here with generic repository. Then you could extend the generic repository for special needs?
Questions About Terminology
1) Is a business object equal to a domain object? How much logic should a domain object contain?
2) Is the domain model the EF model? I am using the Model-First approach.
3) Dependency Injection - Should I be using this? I understand how it works, just don't get the real benefit. I was playing with Ninject.
I think the community would benefit from some sort of wiki that contained all the best practices with code samples. Is there something like that out there? A lot of the samples out there are very simple, and a lot of the Microsoft samples do not use this pattern even when claiming to.
Thanks in advance to everyone who has and will help me with this.
BTW - I think StackOverflow needs a little, "Buy Me A Beer" button next to the "Accept Answer" checkbox :)
Are view models DTO's?
Could be considered a sort of data transfer objects between the controller and the view.
Should they contain just simple properties like Name, AddressLine1, Address City, etc, or should they contain complex properties, multiple objects, etc.
Ideally simple properties but could also aggregate other view models but no models there (ex: like EF models).
Is the validation in the view model.
There are two type of validation logic: business validation (ex. username already exists) which goes into the service layer and UI validation (ex: username is required) which goes into the view model.
Can the view models just contain the POCO classes returned from EF, or should I be using the AutoMapper?
No EF in view models. View models are POCO classes with simple properties and other complex properties pointing to other view models. They could also contain methods in order to properly format the data that will be presented on the particular view those models were intended for.
If using AutoMapper and DTO, are DTO's clones of the POCO classes?
Not sure I understand this question.
Would you map in the controller, view model, or in the service layer below?
The controller.
To me, the service(s) are objects that contact the repository(s) to get POCO objects back from the EF. This is where all of my business logic is. Once the service hands an object back to a repository to be persisted to the EF, they are considered valid objects. Is this correct?
Yes.
Is the domain model the EF model?
If you are using EF Code first approach then yes, otherwise no (if EF pollutes the domain with EF specific attributes and classes).
There is no business logic in them, they are just used to transport objects between the service(s) and the EF. Is this correct?
Yes.
I am implementing Interfaces here with generic repository. Then you could extend the generic repository for special needs?
Yes, but don't get too fancy. Normally Repositories are for CRUD operations. It's services that should contain the business logic.
Is a business object equal to a domain object?
Yes.
How much logic should a domain object contain?
This will depend on the amount of domain logic you have for the particular project you are working and on any existing domain logic you could reuse from older projects you or someone else have worked on.
Dependency Injection - Should I be using this?
Yes, absolutely.
I understand how it works, just don't get the real benefit
It provides weaker coupling between the different layers of your application which in turns makes them easier to unit test and reuse in other projects.
I think the community would benefit from some sort of wiki that contained all the best practices with code samples.
I agree.
Is there something like that out there?
I doubt it.
BTW - I think StackOverflow needs a little, "Buy Me A Beer" button next to the "Accept Answer" checkbox
Can't agree more.
Related
I'm starting to develop an application, and I want to know the best practices to organize the architecture of the solution.
Should I use EF Class Model as my ViewModel?
Should I put all my queries and db access in the model? or create a Service to manage all Db concerns ?
I'm using EF with DB First, because the db is already developed.
Thanks!
There are much more complete descriptions of application architecture out there, but here's the $.25 description.
EF Class Models are for your communication with a data store
Data Transfer Objects (DTO) are how modules communicate among themselves
(WebAPI to MVC, etc.)
ViewModels supply the data your UI requires
Look up "Separation of Concerns" as it pertains to application architecture, it can save your butt. Often, developers will dual-purpose these entities leading to some hilarious results when you find you've painted a corner for yourself. Not so funny if you are the "painter".
On the other hand, keeping these models requires extra effort and the mappings take CPU cycles. Here's a concrete example:
WebAPI accesses People entity (EF class) and maps to a PeopleDTO (not all fields, maybe additional information) and returns this to your MVC controller. MVC controller takes the PeopleDTO and merges it with supporting lookup tables (more WebAPI calls) to create a PeopleVM (ViewModel) that is used by your Razor Page.
In the scenario I just outlined, there are three different types of People object but each could have very different contents dependent on the needs of that "layer". Lots of tools exist to make the mapping less painful.
Clear?
I'm working on a database application that manages industry-specific inputs and then runs that information through somewhat complicated calculations, lookups, etc. to return a series of other values and a go/no-go conclusion.
I've decided to use Entity Framework (code first for provider independence) and WPF (MVVM pattern). I'm using the POCO entities as my data model and the view model is handling the usuals like basic data / business rule validation.
It seems EF + WPF/MVVM are great at displaying and validating input and getting it into the database for querying for your typical business application like a products, customers, orders setup. But it's not at all clear where to plug in a "calculations layer". Between the view models and the data models (my POCOs), things are already feeling a bit bloated, and now I'm facing adding another layer very much like the other two.
Perhaps the best way to approach this is to make the calculations layer a sort of meta-view model and push as much of the validations, change notification, etc. into them and run with lighter actual view models.
Anyone run into a situation like this?
Edit
Turns out what I really needed was to thin the view models and beef up the entities. So I lightened the view models, moved property change notification and basic validation to entities to allow for direct binding, and made calculation classes directly consume entities as well as adding some basic routines to entities. Thanks for the links on thought ADM articles #Peter Porfy.
For moving validation closer to entities, used Fluent Validation (excellent suggestion #Gloopy!). To make it easier to implement property changed notification on entities, adapted this technique. And to avoid having to create endless property wrappers in view model (to set HasChanges property) I used Josh Smith's PropertyObserver.
MVVM stands for Model-View-ViewModel, where the Model layer contains everything what models your actual domain problem.
So it depends on what you mean 'calculation layer'.
Put it where it belongs.
If the actual operation belongs to a domain entity, then you should put that logic into the entity. Don't make anemic domain models:
Article from Martin Fowler about ADM.
DDD works perfectly with EF code-first.
If something doesn't belong to any entity then probably you should expose that as a service. Then use that from your viewmodels through an interface.
A dependency injection container could make your life easier here, but you can live without it.
You aren't plugging another layer because it's the model layer. Your viewmodels should stay as thin as possible, just modelling your view's state and forwarding actual business operations to the entity/service classes.
I'd probably create an interface/object to handle calculations (or several if they can be split up logically) and pass that object in wherever you would want to use it. You might benefit from using a dependency injection framework maybe this post can help with that so you wouldn't have to explicitly instantiate your objects where you need them.
Also this post mentions FluentValidation.NET which may not apply completely but there are likely some good patterns to learn from/use there as well.
im doing some self-study on architecture of a MVVM-light - EF Application
im trying to build a product/Receipt like app.
I have a Db/EF with a Product and Receipt Table/Entity in a many to many relation.
then i have a DAL wich simply uses Linq to do simple CRUD.
the question is where and how to put my business logic in this app.
a couple of ideas came to mind
option 1
-make a ReceiptBo (Receipt business object)
wich inherit the Entity Receipt class and Icollection(ProductBo)
the ReceiptBo class would be responsible for adding Product,calculating total and subtotal and calling the Dal for inserting.
maby this option seemed a little overkill.
option 2
-put the calculating methods in the generated Entity objects by using partial classes
and simply using the BuisnessLayer to call the Dal.
this would make the Buisnesslayer Classes obsolete in my opinion and im not sure that Entity classes should be used for Business logic at all ?
option 3
-make the Business Classes but dont bother using inheritance, just add products to the Entity's and do the calculations there and call the Dal for insert.
wich seems simple but not very elegant.
option 4
-none of the above and im clueless
right now im not using WCF but the idea is that i want to make this app loosly coupled so that it would be easy to implement it and further extend it.
also im a little confused about what an Business layer is. in some examples it is more used like a Dal that also does the computing, then others say this is not done.
some help would be great. thx
ps: sorry for my bad english
Really, I would go simple here and choose a common multi-tier architecture designed as follows:
a data access layer (basically, your Entity Framework model along with all your entities)
a business layer that exposes methods to access to your entities (CRUD methods + any custom method that run some logic)
a service layer that exposes stateless methods through WCF (service+data contract)
the presentation layer (in your case using MVVM pattern)
Views (XAML pages)
ViewModels (C# classes)
Model is represented here by the entities that are exposed through WCF by the service layer
I wouldn't add any method directly in the entities. All methods are defined in the business layer, and exposed by the service layer.
Usually I keep my business logic in my ViewModels, not my Models, and I view EF objects as Models. At most, they'll have some basic data validation, such as verifying length or required fields.
For example, an EditRecieptViewModel would validate business rules such as verifying values are in a specific range, or verifying that users have access to edit the object, or performing some custom calculations when a value changes.
Also, don't forget that ViewModels should reflect the View, not a Model, so not every Model will have a ViewModel of its own
In MVVM, can the model bit be a Domain Model, or can it also be classes generated by Linq2SQL or EF?
Yes and no! The business layer & data layer of your application would consititute the MODEL as far as the MVVM pattern goes.
If your app is anything other than short lived and simple I would implement the MVVM model bit as two distinct layers; a business layer with the domain model and its corresponding data access layer.
As a big fan of DDD (domain Driven Design) I would advocate a domain model that is as close to POCO (Plain old CLR Objects) as you can manage. Use the Repository pattern to isolate those classes (which should effectivly be nothing but the application's business logic) from the nuts and bolts of data access. In the data access layer plonk all the EF or LINQ-to-SQL code.
Data acess code in a data access layer, business logic in its own layer. The two are different and deserve their own focused application layers IMHO.
If I understand MVVM correctly, the point of the pattern is that the ViewModel acts as a presenter between the Model and the View; it takes in a Model, and puts it / adapts it to a form that is understandable by a View. So in that frame, your model could be pretty much anything.
Given my understanding of MVC and DDD (critique as necessary):
Domain Models can be created by Factories, and persisted by Repositories. These are POCO objects.
View Models contain partial or complete Domain Models as needed by the view. They are generated by a service that interacts with a repository. Thus Domain Models never make it to the view directly. Likewise, ViewModels are never persisted.
You will very likely have multiple View Models for the same Domain Model because you could show it on multiple views.
That said, adding data validation to the Domain Model removes any kind of redundancy.
So how do you get the ViewModels to inherit the Domain Model data validation?
I wouldn't expect simply referencing a Domain Model from a View Model to work.
I asked this same question at the patterns & practices summit last October while speaking to Brad Wilson and he did not have a global solution.
One idea I discussed with him was extending an object mapping library such as AutoMapper to also map validation from the domain model to the view model.
In designing a framework to facilitate this scenario, some things to consider:
Validation rules may depend on the context and thus may be unique to the particular view model. The Enterprise Library Validation Block allows the setup of validation logic using a configuration file - this for example, could be extended to transfer to view models as well.
The View Model could have properties which are not part of the domain model, such as a property that specified that a certain "agree to terms" checkbox has been checked. This property requires validation however it is specific to the view and use case, not the domain model. This scenario serves as another argument to keep the validation logic separate, at least partially.
For the purposes of maintenance and clarity it may be easier to duplicate certain validation logic for the domain model and view model instead of using a mapping framework.