Separate Models between 2 MVC projects? - asp.net-mvc

I have 2 Projects. A mobile application and a standard website.
I want to share my models between the 2 projects using Entity Framework - Code First.
How do I acheive this?
I looked at this Q:
MVC and separate projects,
does this mean I should only put my DTOs in the separate assembly?
Is it possible and/or wise to put both View Models and DTOs inside a separate project?
If so, can I also put my model queries inside this separate assembly?
And an example to help project my thoughts:
ExtAssembly.Product product = new ExtAssembly.Product();
product.Name = "Dave";
ExtAssembly.ProductQueries.Create(product);
var products = ExtAssembly.ProductQueries.Search("Dave");

Is it possible and/or wise to put both View Models and DTOs inside a separate project?
Yes, it is possible, however, it might not be the right separation. View models usually are bound to the View, so they would usually stay closer to the View than the Model. I'm not sure what role your DTOs are playing here, but you want to ask yourself what concern (M,V or C) owns them and then group them there.
If so, can I also put my model queries inside this separate assembly?
Based on your example, placing the Model and your model queries in a separate assembly seems sensible. I have seen the Model separated into a new project many times. It doesn't make sense always to package the Model in the same assembly as your controllers or view for exactly the reasons you are stating in your question.
Namely, you usually want to use your Model (where the core business logic exists) for more than one UI.

Related

Business logic layer in ASP.NET MVC - Architecture

I am fairly new to ASP.NET MVC. I am really confused about the architecture of my project. Let me explain my confusion to you guys:
In my project I have three parts which are know to all of us. These are: controllers, models and views.
Controllers reside inside Controllers folder, views go inside Views folder and models are inside Models folder.
As we all know there are two types of models: data model and business model. The data model has all the data types to be used in the project and the business models do have additional logic related to the project. In addition to it there is going to be a data layer of the application which talks to the database.
I am going to create a class library project for this data layer which will talk to database. Also, Models folder of my MVC project is going to have data models only and I am going to create a different library for business model classes as well.
Now the problem I am facing is this:
Lets say the name of my MVC project is MVCProj, name of data layer project is DataProj and that of business layer project is BusinessProj.
If I define the data types inside Models folder of MVCProj, I have to include its reference in both BusinessProj and DataProj projects. Also, I then have to use BusinesProj classes in my MVCProj. Thus I have to add reference of BusinessProj in MVCProj which results in circular dependency.
I am not sure if the architecture I am envisioning is correct or not. Please help me sort it out.
Arsen's answer already explained very well, but I just wanted to post my own experiences (and that's too long for a comment.)
Your idea of separating Business logic and DataAcess is good. Most projects I worked on are organized in a similar manner.
What I would do in your case is:
1 - Create a project for DataAcess: MVCProj.DataAcess
2 - Create another project only to contain your database Entities: MVCProj.Entities
3 - Add a reference of MVCProj.Entities in your MVCProj.DataAcessproject
4 - Create a project for your business layer: MVCProj.Business:
5 - Add a reference of MVCProj.Entities and MVCProj.DataAcess in your MVCProj.Business project (I'm assuming business layer will call database)
6 - Add a reference of MVCProj.Entities and MVCProj.Business to your MVC project.
See the logic? Each layer is responsible for doing "its job". Now MVC controllers may call business, wich call the database to save the records. All projects share the same Entities.
The "Models" folder on the MVC project is just an example the team provided. In most examples in the web you see people calling the database (Mainly using Entity Framework) directly inside the controllers. This works, but in the long run is very bad to maintain.
Another thing most people do is: You usually don't want to return your database entities in your controllers. Perhaps they include more properties than you will need and etc. In this case you can create what is called a ViewModel. Think of a ViewModel of something like a copy of your Entity class but only with fields relevant to the View. The ViewModels are specific to the MVC project, so they will stay in a folder inside the MVC project. You may call it Models, or ViewModels, your choice.
Not going much further, but with the separation of projects I showed above you can definetly look for a Dependency Injection framework to handle all the creation of instances of the classes for you. :)
Note: It was implied but all projects except the MVC one are just plain old class libraries.
Hope this helps clarify your ideas.
There is no silver bullet in Architecture, all of this is not a must, but depends from the project...
The amount of layers in your application strongly depends on the requirements.
On the one hand additional layer separate the concerns(example: from DataAccess to Business Logic) on the other hand with each level you increase the amount of work, and decrease performance
Regarding your question, it is ok, when one layer depends to another, it is not ok that the third layer depends on the first one...
In your case you choose 3 level, ideally it should look like this
DataAccess, with its data classes in separate project
BusinessLogic, another project, which call data access, and convert result to its data classes
And finally on the model reference BusinessLogic only
I did a write up that I think my help some of your confusion: Entities are not Models.
TL;DR The main source of your confusion here seems to be that you think you need your "data models" (entities) in the Models folder of your MVC project. That's incorrect on two fronts. First, the Models folder is pretty meaningless. You can rename it, remove it, whatever. It doesn't effect your application at all. Second, and as the post I mentioned details, entities are not models. They are, and should be, merely representations of a table structure to give your ORM (Entity Framework, likely) some place to stuff the data it retrieves from the database.
That said, the typical approach is something like the following:
"DAL" class library containing your context and entities. This is where your migrations will go.
A "business" class library that essentially wraps your DAL and provides basically an API that your MVC project can use to get at the data. Depending on the complexity of your app, this is the layer that's most fungible, as you'll often need to draw a fine line between what is "business logic" that might be universally applicable to any application your organization develops vs. "business logic" that is related to the specific application you're developing.
Your MVC project, which will utilize the DAL/Business layer.
In your MVC project then, your Model folder can basically go away, or you can use it for storing view models, instead. It's common, though, to actually create a ViewModels folder for those specifically. However, it's entirely up to you.
One final note. The "business layer", could also just as well be composed of multiple different class libraries. In my organization, for example, we have a library specifically for working with our POS system, a library for connecting to an API we utilize for email lists, a library for working with Elasticsearch, etc. Our web projects just include whatever libraries they need to utilize.

How to simplify MVC pattern for a demo purpose?

I have to set up a Asp.net demo using MVC 4 in a web application in order to help decision for a product that currently don't use this pattern. The model, view and controller should be simple, I just have two or three entities and a few pages.
I suppose I don't have to implement the whole infrastructure with services, repositories, etc. So how could I simplify the MVC components without loosing those advantages?
The MVC components aren't related to the data access strategy which you can use. To put together a quick demo (or a simple application) you can leave the data access in the same project but eventually split that out etc.
You can use something like AutoMapper to map from your entities to your view models if you want to put that level of abstraction in. You can also use EntityFramework contexts in the controllers to avoid additional levels of abstraction and only put in a simple interface/abstraction into one controller to show unit test ability.
Small examples of different patterns which could be used in the application is probably the way to go for the demo/presentation and not worry too much about putting them in all over the place. Remember the presentation and the delivery of information is as important, it not more, than the demo code itself.

ASP.NET MVC - Model in Web project

I'm new to ASP.NET MVC and inherited a project that uses the technology.
Such Web project contains three folders: Views, Controllers and Model. As I understand it, the Model contains in fact your domain / business logic and is called by your controllers. The controllers themselves act as delegators between Views and Model.
Now, in a typical layered architecture, there should be no references in any project to the Web/UI project.
I find this quite confusing:
-> The UI contains the Model, which is - in an ideal world - based on "Domain Driven Design"-principles.
-> The layers on top of the UI (Services and DataAccess) cannot have a reference to the UI
How can you write efficient services and dataaccess layers if they do not know your model?
What am I missing here? Is the Web.Model different from "DDD" and should I still have a separate BL project? If that is the case, then what is the Web.Model supposed to contain?
I view the Model as a concept. You can have a completely separate project containing your Domain (your entities, your services etc.) and reference that in your "UI" project. In this scenario this will be your "Model".
This is what I typically do, In my Models folder I keep "ViewModels", which I use for Binding/Validation (for the UI).
For example, If I have an Employee but I don't necessary want to use all its properties (or for that matter different properties), I will create an EmployeeViewModel adjust it the way I want, I'll add validation (if required) and I'll pass it to my View.
This is by no means, "the right way"/"only way", but It worked for me in the past, and I thought I'll share (also, I'm pretty terrible in explanations, so I really hope this post makes sense, in case it doesn't or clarifications are needed - please let me know).
You necessarily do not need to have your model in the same project. You can ofcourse have those in different layers.
This is how i usually setup my projects
1) UI Project - This is an MVC Web application type project where i will have my controllers and it's views and other UI related stuff
2) Business Entities - This will be a class library type project where i will define my domain objects ( Ex : Customer). This mostly looks similar to how my DB schema looks like. These are usually just POCO's which represent my domain modal ( I use this for the CodeFirst Database generation).
3) Data Access - This will be another class library type project which has the data access classes. Usually my repository class/interfaces, my DBContext class and other data access classes will be in this project.
4) Tests - Unit tests for the project
Business Entities project has been added as a reference to the Data Access Project so that i can use those classes in my Data access code.
Business Entities and Data Access Projects are added as references in UI Project. I would call the data access methods from my Controllers/ Service classes.
You may also add a Service/Business logic layer between your controller's and Data access layer as needed.
I have few ViewModel classes also inside my UI project ViewModels folder. I use this for some screens where i have to show data from multiple domain objects. I have a mapping/service class which maps the domain object to view model object. If your project is bifg, you may keep this as a serperate project under the same solution
Views Contain your HTML Layouts
Controllers do the heavy lifting of getting data from the models or the models themselves and passing them to the Views.
Models are used to do actions for your BL or fetch data.
Tip : You can use a EntityFramework ( i'm recommending it because it's easy to get started with ) to fetch your data and it's dead simple to setup thus eliminating your DAL and saving you time from writing everything yourself.
Services : you can have controllers that return XML/JSON (other format?) by converting the data you have got from the DB to XML/JSON and returning that instead of a view.
Take a look at MVC 4 WebApi for more details,Note that you can pretty much the same thing with mvc 3 too
Also refer to asp.net/mvc site for tutorials to get you started, they are really useful.

ASP MVC 3: Is dependency injection in ViewModels a good idea?

I am facing a design issue with an mvc 3 app. I have a viewmodel ProductCreateModel that has a list of Categories.
Now I am setting the Categories list in the controller, but I am thinking if it is a good idea to indect the datasource in ProductCreateModel constructor.
Do you think that view models should be fat models that also know to read dependent data from the data source? ... or this is a controller thing?
I prefer slim viewmodels that do not know a thing about data layer. They are easier to manage (in my experience).
I think view models should be light models, and the only way for them to read related data, should be properties on "parent" object, the model they actually wrap.
Most of the time my view models are just classes with properties, all logic are in the controller or in a service class (if we're talking a lot of logic that would otherwise be put in the controller). All this is in the name of easier testing.
When I learned MVC I was taught that the "rule of thumb" is Skinny Controllers, Fat Models, Dumb Views. A mistake that many MVC developers make is Fat Controllers (too much logic), Skinny Models (basically POCO classes to hold data), and Smart Views (a bunch of Razor Syntax with If this, Else that, etc.)
Over the years I've stuck to the Skinny Controllers, Fat Models, Dumb views approach, and it has worked well for me. Now, take into consideration that this is related to Models and not ViewModels. Usually your Models should be in an entirely different layer (i.e. proj or folder). ViewModels, on the other hand, should be fairly simple. This makes them easier to test, and more reusable. If you are finding that you need some sort of service, repo, or other dependency to build up your ViewModels, then you should probably abstract that logic out into some sort of Composer Class. In the past I've used a ViewModelManager which implements IViewModelManager, to compose my ViewModels if need be. This way you can inject IViewModelManager into your controller, and use it to build your ViewModels. Then, in your ViewModelManager implementation, you can inject your other dependencies, like repos, services, etc. to actually construct your ViewModel.
This approach definitely requires more code, and many more classes, but it will give you a good level of granularity, and separation, plus support the DRY principle along with Single Responsibility.
Happy Coding!
As a general rule, I don't think you want to do that.
As an exception to that rule, I've started using a little bit of Service Locator in my Editor Templates when creating drop downs. I've gone through multiple ways of populating drop downs (generally, some form of adding a collection to either the view model or into view data). I saw a video where SL was used in the Editor Template to get the data and then convert to a Select List. My initial reaction was "ugh, really?", but, the more I thought about it, it made sense.

Where to put a ViewModel factory in my ASP.NET MVC app?

I have a fairly complicated ViewModel associated with a product listing form, which has a lot of custom default values depending on the currently logged in user. I'm finding that populating it in my controller is quite a chore. So I'm thinking of creating a factory class for it, but I'm wondering where in the project structure it would be a best fit. In the Controllers folder?
I'd move it out into a separate Common or Core folder, or Common or Core project for that matter. If you can decouple the logic that's not specific to MVC, you'll probably be better off in the long run.

Resources