ASP.NET MVC 3 best practice / design - asp.net-mvc

I have spent a lot of time searching for best practices for designing a ASP.NET MVC 3 web site using EF 4.1 or another ORM. I found this tutorial on Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application . It was a good tutorial and I learned something. So this got me thinking and wanted to know from the people on stack is this something you would use? if not why and how did you design your web site? I just want to learn the correct way to do things and understand why one way is better then the other.

First to say Entity Framework implements a Repository pattern and a Unit of Work Pattern. Implementing Repository and Unit of Work patterns on top of a modern ORM like Entity framework is an additional layer of abstraction that:
narrows the possibilities of the underlying ORM
does not provide additional value to the underlying ORM
is at best worthless but may be harmful
One purpose of such implementations is to encapsulate the query logic in the Repository and not one query like Single Responsibility Principle (SRP) would suggest, but a couple of queries and thus violating SRP. What you could do is to rely on your ORM and encapsulate extensive query logic in single Query classes.
My suggestion is not to please "best practices" by adding abstraction layers on abstraction layers and so on but to try to solve a problem using some more general design guidelines such as SOLID.
Ayende Rahien reviews the Northwind Starter Kit application in a series of blog posts (here, here, here, here, here, here, here and here) in his blog that deal with so called best practices applied in an application. This is a great read!

Related

ASP.NET MVC with service layer and repository layer, where should the interfaces be defined?

I am in the process of determining a fairly simple layered architecture for a .NET MVC application that has a repository layer and a service layer. I have found some fairly clear and simple examples, notably www.asp.net, and some questions and answers here, but I am looking for something that is a little simpler, suitable for small applications, but that uses different projects, to get the idea across. The example I linked to above has the repository and service as classes in the Models namespace. That just isn't enough of a clear separation for me to be able to illustrate it properly.
I have a separate project for the repository that implements interface IRepository. There is a separarate project for the Service that implements IService and takes an IRepository (constructor injection). The Service implements IService. It is enough for this example that the controller instantiate the service, no need for an IoC container just yet. Think of it as an intermediate step to understanding best architectural practices, part of a sequence that builds progressively to include dependency injection and possibly more layers.
The question is, where should I define IRepository and IService? Both the service and repository projects need to reference them, of course. It seems clear then that they should be defined in another project referenced by both the service and repository projects. If so, what would a good naming convention be? Something like XXXXContracts?
Likewise, for the data models passed between the presentation, service and repository layers, is it acceptable to have a separate project called XXXXModels referenced by all the layers? I understand that in some cases the models passed between the service and repository layer can differ from those passed between the service layer and the presentation layer, but the principle is the same.
I have found answers to similar questions here, but they tend to involve a more complicated architecture than what I have outlined here. I'm looking to achieve a really simple and clean illustration of the two layers that can be seen as a step or two above referencing the data layer and having business logic in the controllers, that's all. I know there is a strong and valid argument for going straight to the full-blown best practice, but not everyone is suited to making that jump in one go.
Introduction
This is something I've asked myself as well. One burning question I always have is similar to yours;
what would a good naming convention be?
How should I name things? Should they go in folders or projects?
After searching around I suspect the answer is that it doesn't really matter. What's important is that you solution has some sensible architecture and that you try to follow good practices such as SOLID.
My ASP.NET MVC heroes on this topic are Jeffrey Palermo, Steve Smith and Jimmy Bogard.
Onion Architecture
Jeffrey Palermo discusses a combination of old ideas but brings them together and gives it the visually stimulating name of Onion Architecture (a recommended read). Jeffrey shows a good approach to the problem of where to put things. He explains that at the centre (or top) of your application you have your Core. This layer is where you should put interfaces such as IRepository and IService.
Almost all of your interfaces should go in the core and everything else (other projects) can all reference the core. This way everything knows the skeletal structure of the application without knowing the implementation details.
Try to have your UI layer reference as little as possible (within reason). In one of my applications my UI (MVC) layer only references the Core. Everything it needs is injected into it with Dependency Injection.
Steve Smith discusses Onion Architecture and similar ideas with demonstrations in MVC Solution Best Practices: A solution to the solution problem
My solution
In my MVC solutions I have a typical structure like this:
MyProject.Core
MyProject.Domain
MyProject.DependencyInjection
MyProject.Infrastructure
MyProject.Web
MyProject.Tests
The Core contains my interfaces. It is usually divided up into folders like Services, Models, Domain, Repositories and so on.
The Domain layer references only the core and contains my implementation. It provides a lot of the concrete classes for the domain abstraction in the core. It deals with a lot of business logic, processing, command handling, manager classes, concrete service implementations and so on. I consider it a fairly inner-layer and so it references as little as possible.
The DependencyInjection layer contains my chosen DI package/framework and implementation details. I consider it an outer layer; similar to UI or Infrastructure and so it's ok if it references a lot. It's not necessary for this layer to be a separate project and many people will tell you not to do this. That's ok; do what works for the complexity of your project. I like my DI to be its own thing. The good thing about it being so separate is that I could replace the DI framework with a different one and things would be fine. No layers reference the DI project.
The Infrastructure layer contains information about logging, emailing and data access. It will contain my ORM of choice. It's not business-logic stuff and it's not UI stuff. It's the railroad of my solution to get things done. It's on the outer layer but it only references the Core.
The Web layer is my MVC project and only references the Core.
Complexity and final thoughts
I have found answers to similar questions here, but they tend to involve a more complicated architecture than what I have outlined here
It's a good point. It's important to keep in mind the complexity of your problem. But don't be deterred by good solution practices. My solution and Onion Architecture are not necessarily very complex and don't really bloat your solution. They just keep things separate.
In Evolutionary Project Structure, Jimmy Bogard talks about things being over-complex. If what I've said seems too complex, follow Jimmy's advice and put it all in the one project (your UI layer). That's ok - as long as it suits you.
Remember to take my solution only as an idea - something to consider; my approach is an attempt to follow sage advice from the best, but I'm sure I've only succeeded so much; I can (and must) still improve.

Which pattern is appropriate for my project?

I've been seeing a lot of articles and references about how to use this patterns for my first (please keep this in mind) serious project with ASP.NET MVC 3 and EF.
The project is not so big (13 tables) and it's basically a CRUD maintenance: organisations that have some users; users that can belong to a group and can create some work areas and templates... Nothing complicated. The point is that this will be the first of a project series and I'd like to create a base to work with.
My questions are:
Which of the previous patterns is the best? Does it depend of the project size?
My models would be these:
Unit of work
Dependency Injection
Do you think they are good enough and appropriate for my project?
I appreciate all your comments.
Serious application doesn't mean to be complex at first sight.
Over engineering an application upfront can be a real disaster, especially if you don't grasp all the technologies involved.
My advice would be to keep it simple. Create a basic application that fulfill requirements (get the thing done and make your boss happy) and then add new concepts along your learning path.
That doesn't mean I promote bad code, no way! Keep your code clean, well organized, etc. But don't be killed by the fear of doing something wrong.
It's normal for a developer to look back to an application made a few weeks ago and then realize that he did some shitty stuff. That's how we progress!
Last but not least, have FUN!
ASP.NET website provides usefull resources to learn the framework and all related guidances. There are a few application samples created step-by-step.
ASP.NET MVC was built with Dependency Injection in mind.
If you want to give a chance to your code to be loosely coupled and easier to change in the future you have to follow the patterns like Dependency Injection, Repository (for presistance abstraction), and UoW (for transaction abstraction).
So my answer is, you should learn about them in the first place to decide after if you want or no to follow the best practices. Even for simple project it's good to apply these patterns because often it gets bigger and bigger. and it's easy to do it in MVC so why to avoid it ?
There is many resources around to learn about. You can just google it.
I would like to answer this question in more generic way. Creating something which can be used in future is difficult than what it seems. All the pattern above can provide you infrastructure pieces to come up with some base framework.
But I would strongly suggest you to look at S.O.L.I.D principals (DI being part of it) to understand some qualities of good code. These are applicable irrespective of the technology involved.
You cannot predict the future requirement of a product\framework, but following these principle you can be better prepare to handle any future modification to the software
You might want to check out S#arp Lite which has many good examples of how to implement the things you want and can serve as a very good base on which to build something quickly.
None of the mentioned patterns are mutually exclusive. You should use the patterns that make sense based on what you are trying to accomplish, not attempt to shoehorn your application design into someone elses idea of how it should work. Sometimes trying to bend your scenario to fit a particular design pattern / practice is the worst thing you can do.
Want to make sure good unit test coverage / do TDD / ensure loose coupling? Then Dependency injection is your friend, as is the Unit of Work pattern. This is definitely a good idea for creating a maintainable, scalable application, but you can go too far with it for a small-scale application.
Need a centralized caching strategy for your data source? Then use the repository pattern. Or an ORM like NHibernate, which might do it for you.

ASP.NET MVC fuzzy path to the pit of success?

I'm interested in adding ASP.NET MVC to my skillset. However my reticence comes from the fact that there seems to be a lot of "fuzziness" when people talk about implementing applications and how to adhere to the rules of the MVC architecture. I've heard Microsoft quoted as wanting developers to fall into the pit of success. With that said my question(s) is:
How do I avoid writing bad MVC code when there is such a variance in the agreement on how a program's structure should adhere to the tenants of the MVC architecture? Is there an agreed upon approach/best practices?
Would I be better served to learn Ruby on Rails(other than to learn a new language) to get an understanding of what inspired Microsoft to create ASP.NET MVC?
Go through the NerdDinner tutorial. It is a step-by-step walkthrough of the process that was used to create NerdDinner.com using ASP.NET MVC. There is general agreement that this application (for the most part) follows best practices in its design and coding.
Also, have a look at Scott Hanselman's File/New/NerdDinner presentation at Mix09. He builds the entire application (more or less) in 70 minutes, with wit and insight. Scott also talks about some of the important surrounding technologies such as jQuery.
You'd probably be better off becoming familiar with the MVC architecture itself. Learning about Design Patterns may help, as MVC can be seen as a composite of Observer, Strategy, and Template method.
MVC has slight nuances when viewed from ASP.NET MVC, RoR, GroGR, CodeIgniter, etc, but it's all essentially built around the same concepts: business logic goes in the model, controllers serve to route to appropriate models, and views should just display data. While there are differences between MVC 1 and the web centric MVC 2, once you understand MVC you can use different implementations of it fairly easily.
Here's a fairly good explanation of it from a software design course.
There's no single right way in doing object-oriented programming at all. Just pick the one that is closer to your taste. And a year after that, your taste will change... that's how our programming skills grow ;-)
For example, RoR takes ActiveRecord path while I personally prefer domain-driven design with POCO business objects. But this comes from my, sometime unconscious feeling of proper OO design. Yours may vary - but that's the exact point, only you can decide what's right for you. And, of course, don't forget that your customers want it now ;-)
ASP.NET MVC is a ripoff of Ruby on Rails in my opinion. I don't mean to sound harsh, Microsoft has done an excellent job and it's a great platform. But it wouldn't do much good to learn Ruby on Rails to see the roots of MVC, they are extremely similar.
That being said, you should really learn the MVC architecture and I would recommend you learn ASP.NET MVC. I think it is very good in certain scenarios, a great separation of business logic from the view.

Why ASP.NET MVC favorites Linq to SQL over LINQ to Entities?

The question is in the title.
It doesn't favor one over the other at all. It's just common to use LINQ to SQL examples because they are simpler to setup and deploy, so it's easier to digest the sample code without getting distracted by something which deserves its own learning path.
I agree that it does not favor one over the other. I always assumed that Linq to SQL tended to be used in examples because it was released about a year earlier. Therefore, book writers were more familiar with Linq to SQL and/or felt it was more stable.
I agree with Rex in that it makes more sense, when giving a tutorial about ASP.NET MVC, to keep other technology decisions simple. Since either DAL implementation can be used, it is easiest to teach MVC by using Linq to SQL (the simpler of the two). Linq to SQL is also widely considered to be more light-weight.
I must admit, it would be nice to have more open-source examples of projects using ASP.NET MVC along with Entity Framework. I can tell you that it works fine, because I am using it on one project. However, it can be a bit more difficult to figure out some of the ideosyncrasies. Here is another question that shows some links to examples.
I think this tendency to use the path of least resistance in example is a diservice to new developers. How many times have you seen an example, with the caveat that it is not production worthy code, with no reason as to why it is not appropriate, or good direction on how to find what is best? Personally, I appreciate longer examples that actually lead me to discover how something should be used are more helpful.
In this particular case, using Linq to Entities would be much more useful, as it is seemingly the future.
In my opinion, it doesn't favor it. It's what you see in most examples, because Linq to Sql is the fastest way to get examples up and running. Rails follows the same convention of many examples using features (scaffolding for example) that you would rarely see used in a production site.
As all the other posters have said - L2S samples are just a lot easier to put together hence you'll see them quoted more. In reality your MVC models may not use L2S directly - they could be hooking up to a separate services tier or some data transfer objects exposed by another system entirely.

Is MVC the best way to code asp.net applications? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
update: I know there is no one best way to do everything. Sorry for not saying that right off. In the context of the data-access tutorials, if you had to do the project he did in that tutorial, would you do what he did or would use use MVC, if you had to choose one of them?
Update: Is MVC the more appropriate way to program asp.net applications, instead of the tutorials found here:
http://www.asp.net/Learn/data-access/
Original:
I ask, because I initially learned about MVC with Java applications, then things like RoR, and Django. These other projects and companies spoke as if MVC had been around for a very long time, and from what I found out it had. Then Microsoft started putting MVC into the .net framework.
I ask because I don't know how to design things very well and thought I was doing well to emulate what's on the asp.net site with Scott Mitchell's tutorial. I thought that creating abstract layers in a BLL was the way to go until I found out about MVC and now asp.net's MVC.
I honestly don't know what the "right" way is to do things. I just create what I need, but I can't help feel like I am missing something.
Is MVC the correct way to start doing things in large projects, specifically I mean MVC and ASP.NET, but could just as well mean PHP and one of their MVC frameworks.
I'd like to settle on a standard way of doing things...for now anyway.
And, out of curiosity, why did Microsoft only now start doing MVC?
UPDATE: Is MVC better than the current tutorial set on asp.net?
I'm referring to the Scott Mitchell tutorials where he creates the BLL for abstraction. Or is that a linq question as well. I should have said that I understand the need for keeping logic and presentation separate but unsure the best way to do it. I was using the asp.net tutorials. It worked fine. Then I found out the rest of the world, as I saw it anyway, was using MVC. Then Microsoft started developing MVC, so to me the other method seems obsolete and the wrong way to do things.
No, it's not the only best way to do things.
MVC is just a design pattern. The goal of all design patterns is simplicity. So as long as it makes your design simpler, go with it. If it makes things more complex for your specific application, try a different approach.
Unfortunately, some people think if they see a pattern, they should use it. It's just not true. Design patterns don't inherently make your application better. They are not an end. They are a means to an end (which is simplicity). So you should use them only if they are worth it.
In my opinion, over-architecting things without a good reason is worse than writing code without any specific design.
EDIT: Regarding ASP.NET MVC: I have a negative personal bias toward ASP.NET Web forms. Before MVC, I did most of the dynamic aspects of advanced projects by writing custom handlers to have fine grained control over the HTML. Web Forms make Web development very easy but they have particularly a couple things that are good but sometimes are problematic. The first of which is ViewState and the second is complex WebControl architecture. Don't get me wrong. Those are signs of brilliance of ASP.NET. I haven't seen a single platform for Web development as easy as ASP.NET Web Forms and this is only because of great WebControl support which requires ViewState. However, in some projects, you want to have precise control on rendered HTML (specially when you have some client-side logic). You also want to make server side code maintainable in large projects. In those areas, ASP.NET MVC really shines. But I think ASP.NET Web Forms will remain a great technology where it's more applicable. After all, as I said regarding design patterns in general, you should carefully evaluate your design to see which one better fits your needs.
Specifically, about data access, MVC usually requires more code than Web Forms counterparts. For presenting tabular data (i.e where GridView is applicable), I think ASP.NET Web Forms is the easier way to accomplish things. However, most data driven Web apps are not just manipulating a table directly in a database. They have complex layout. StackOverflow is a great example of this. It is certainly data driven, but ASP.NET MVC better suits it.
There is no "right" way to do things without knowing what "things" are. MVC is a design pattern that solves a specific common problem - separation of presentational and domain logic. Every design pattern is a commonly accepted "good" solution to a specific problem.
Those solutions, combined with knowledge and experience are building blocks for a good design. The "right" way to do things is to study your problem domain, research on possible solutions and apply the set of solutions that work best to solve it. Making mistakes is a part of the process as well, so don't be afraid to experiment and then refactor with rigor until you reach the solution that serves you best.
MVC is the worst way to develop applications, except for all other ways that have been tried. :-)
Joking aside, MVC is one application design that encourages us not to write spaghetti code. It's a guideline that reminds us to keep business code separate from presentation code. This is very helpful as the application gets more complex.
There are other variations that achieve that same benefit, but are not strictly the same as MVC. Presentation-abstraction-control (PAC) is one example.
As for why Microsoft is so late in adopting MVC, I'm not surprised that they are. They are pretty well-known (at least in recent years) for being conservative instead of innovative. They prefer to let other smaller companies take the risks in an unproven market, then they learn from the mistakes, churn out an overengineered competitor solution, and dominate through marketing.
Example: Microsoft Internet Explorer was considered to be a latecomer to the browser market. Netscape had become very popular, leading the way in providing a platform for people to view HTML. Once the amount of HTML content on the Internet was at a useful level, Microsoft belched up their onomatopoeic "IE" product and quickly captured an overwhelming market share.
MVC is just one way of doing things. I like it because it helps to promote extensibility and is structured to allow testing and code reuse. There is no silver bullet, one true way to do everything but I use it quite often.
In regard to Microsoft, I would say that they adopted the pattern as an alternative to WebForms development for the reasons I mentioned above. I would recommend looking at Rob Conery's MVC Storefront and kind of play around with the examples to see how it works for you.
There is no "best" way to code things. It depends on the application in question; sometimes MVC is the right choice, and sometimes it's not. A good developer is able to weigh his/her options and choose the one that's best suited for a task at hand, instead of just going with the method du jour
If MVC solves the Primary Technical Imperative of managing complexity in your application then it may be a good solution, but it is by no means the only solution.
MVC is one of any number of design patterns. Whether it's the best technologically, or the simplest, or for what types of projects it's appropriate, are are all arguable (see other SO threads). In any case, few would argue against the prevailing consensus that for most cases, it's "Good Enough".
But it has the undeniable benefit that a lot of people use it, on a lot of different platforms.
So if you want to use a methodology that is likely to be around a while; or you don't want to depend on one vendor for support and extension and refinement; or you work in a group that would like to grow by hiring people from various backgrounds who will grok a shared methodology quickly; or you would like to maximize your opportunities to move on if you need to, then MVC is one of the very best ways to support those goals.
MVC being "Better" or "Worse" pattern is relative to the project.

Resources