What is the service layer in an ASP.NET project? - asp.net

I'm having problems to understand the conception of DDD. I have an ASP.NET project with this structure:
ASP.NET MVC4 project: xxx.UI.Web
Class Library project: xxx.Application xxx.Domain xxx.Infra.EF
I'm trying to keep this relation:
xxx.UI.Web only have relation with xxx.Domain and xxx.Application
xxx.Domain doesn't have relations.
xxx.Application have relation with xxx.Domain and xxx.Infra.EF
xxx.Infra.EF have relation with xxx.Domain
But now I'm having many problems to keep this concepts with Entity Framework. I have created the Entity repositories in the xxx.Infra.EF and created a generic repository (with interfaces and so on) in xxx.Application.
The problems begin when I need to pass a personalized Entity context to my repositories, because I use the repositories in the xxx.UI.Web and I can't instantiate a new Entity context because It will broke my project pattern (The Entity context comes from xxx.Infra.EF).
My idea is to create many helper methods that will process this kind of operations for my xxx.UI.Web, and I wouldn't like to create this methods in xxx.Application (It looks a little strange to create many methods with a little relation with my business logic).
So I was reading a little about Domain Driven Development (DDD) and I knew about the Service layer, and I think It seems to be the layer that was created to solve problems like this, or not?
My idea is to create a new class library project called xxx.Service and make this project keep relation with xxx.Domain and xxx.Infra.EF. Is It right? I know that I could search for another solutions for my case with Entity context, but I guess I'll have more problems like this in the future with other things, so I tried to find solutions for It. I should study much more about It, but I think I could identify the solution for my problem.

I suggest you further study the concept of layered architecture.
You are correct that the Domain should not reference other layers, such as the Presentation Layer and Infrastructure Layer.
The most common style of layered architecture is the "Onion Architecture". See image and link below.
http://jeffreypalermo.com/blog/the-onion-architecture-part-1/
The Service Layer
You are also correct that a new layer (Service Layer) will solve your problem. You see, the problem arises because the UI/Presentation Layer is talking directly to the repositories(Infrastructure).
In our approach, the Presentation Layer does not communicate directly with the Infrastructure and Domain. We have a Service layer that comes between the Presentation and the Domain.
The above architecture borrows heavily from the Onion Architecture. We don't have domain services. Application Core is our CrossCutting Layer.

People often misunderstand the point of a multi-tiered application. The goal is not necessarily to remove dependencies, but rather to encapsulate and modularize code. Your MVC frontend shouldn't need to be concerned with your entities and how their queried, added, updated, etc., but it doesn't mean it doesn't need access to them. Long and short, don't focus on project references, but rather factoring out code that is not in each project's "domain" into a more appropriate "domain".
To that end, it's not really possible to say based on the information you provided exactly what you should do. The question is opinionated to begin with and will very likely end up being closed as a result. Ultimately, you have to decide what's best for your project. Do what makes sense, rather than blindly following some pattern. After all, patterns are supposed to just be a codification of common sense approaches to common problems, anyways.

Related

Designing an Asp.Net MVC application

As a novice to this realm, I am planning on building an mvc application. I had originally started a web forms application but decided the scalability and testability will benefit more with an mvc application. I chose to switch with the added benefit of being easier to add more features later on (instead of having code baked into web forms pages).
Now a little about my application, it is an application to stimulate an RPG class builder and moveset. In all simplicity, users can register for a class, and depending on other skills they can register for, they can see a custom move set based on these categories. The way I am envisioning it is I will be able to go back and add more classes and skills later in the database and have users register for this new content immediately once it has been added to the project.
Everything lives in normalized tables, so many joint tables do exist. For each new skill or class I add will mean a handful of tables will be added to the database. This speaks to the way the data will be stored, everything and all information about classes, user data, skills, etc will be stored in the database.
I have designed all the initial database tables I will need to have at the start, and functionality I need (a home page, view skills page, view move sets page, etc.). I am stuck at the next step; where do I go? Should I make my controllers first? Models? Views? Design my page layouts? I am asking for advice from people who have taken a similar organic approach to an mvc project. I am facing analysis paralysis on what to start on, knowing I have a lot of work ahead of me.
Thank you for taking your time to answer.
I've taken everyone's advise and am putting together a website to learn MVC: http://learnaspnetmvc.azurewebsites.net
The most important advice I can give you: just start. A big project can seem overwhelming, especially when you're looking at it like a big project. Instead, break it into small achievable tasks. Find something you can do right now, the ever-so-smallest subset of functionality, and do it. Then do the next one. And the next.
That said, I'll tell you my personal process. When I start on a new application or piece of an application, I first like to create my models. That way I can play with the interactions between them, flesh out the relationships, and think about the needs of my application in a somewhat low-pressure, easily disposable way. I also use code-first, whereas you've gone an created your database tables already. Some people prefer to do it that way. Personally, I find starting with my classes and letting those translate into an underlying data store much more organic. In a sense, it relegates the database to almost a non-existent layer. I don't have to think about what datatype things need to be, what should be indexed and what shouldn't, how querying will work, what kind of stored procedures I need, etc. Those questions have their time and place -- the nascent development stage is not that time and place. You want to give your brain a place to play with ideas, and classes are a cheap and low-friction medium. If an idea doesn't work out, throw the class away and create a new one.
Once I have my models, I like to hit my controllers next. This lets me start to see my models in action. I can play around with the actual flow of my application and see how my classes actually work. I can then make changes to my models where necessary, add additional functionality, etc. I can also start playing around with view models, and figuring out what data should or should not be passed to the view, how it will need to be displayed (will I need a drop down list for that? etc.), and such. This, then, naturally leads me into my views. Again, I'm testing my thinking. With each new layer, I'm hardening the previous by getting a better and better look at how it's working.
Each stage of this process is very liquid. Once I start working on my controllers, I will make changes to my models. Once I hit the views, the controllers will need to be adjusted and perhaps the models as well. You have to give yourself the freedom to screw up. Inevitably, you'll forget something, or design something in a bone-headed way, that you'll only see once you get deeper in. Again, that's the beauty of code-first. Up to this point, I don't even have a database, so any change I make is no big deal. I could completely destroy everything I have and go in a totally different way and I don't have to worry about altering tables, migrating data, etc.
Now, by this point my models are pretty static, and that's when I do my database creation and initial migration. Although, even now, really, only because it's required before I can actually fire this up in a browser to see my views in action. You can always do a migration later, but once you're working with something concrete, the friction starts to increase.
I'll tend to do some tweaking to my controllers and obviously my views, now that I'm seeing them live. Once I'm happy with everything, then I start looking at optimization and refactoring -- How can I make the code more effective? More readable? More efficient? I'll use a tool like Glimpse to look at my queries, render time, etc., and then make decisions about things like stored procedures and such.
Then, it's just a lot of rinse and repeat. Notice that it's all very piecemeal. I'm not building an application; I'm building a class, and then another class, and then some HTML, etc. You focus on just that next piece, that small chunk you need to move on to the next thing, and it's much less overwhelming. So, just as I began, I'll close the same: just start. Writers have a saying that the hardest thing is the first sentence. It's not because the first sentence is really that difficult; it's because once you get that, then you write the second sentence, and the third, and before you know it, you've got pages of writing. The hardest part is in the starting. Everything flows from there.
The other answers here have great advice and important nuggets of information, but I think they do you a disservice at this stage. I'm the first to advocate best practice, proper layering of your applications, etc. But, ultimately, a complete app that follows none of this is more valuable than an incomplete app that incorporates it all. Thankfully, we're working with a malleable medium -- digital text -- and not stone. You can always change things, improve things later. You can go back and separate your app out into the proper layers, create the repositories and services and other abstractions, add in the inversion of control and dependency injection, etc. Those of us who have been doing this awhile do that stuff from the start, but that's because we've been doing this awhile. We know how to do that stuff -- a lot of times we already have classes and libraries we drop in for that stuff. For someone just starting off, or for an app in its earliest nascent stage, it can be crippling, though. Instead of just developing your app, you end up spending days or weeks pouring through recommendations, practices, libraries, etc. trying to get a handle on it all, and by the end you have nothing really to show for it. Don't worry about doing things right and do something. Then, refactor until it's right.
As a first step in planning a MVC framework application, We should start with a strong Model (typical C# props). This process is going to take most of our time, based on the fact that we need to understand the business first and then the relationships between different workflows and entities. So times business models evolve as time passes. So spend qualitative time on building this layer, but not too much.
Once domain (Business) Models are ready, before we actually start coding for Repository classes, we should define our Repository Contracts which are typically Interfaces. Contracts help all parties(other components) to interact with each other in the exact same way. Then we implement contracts on the Repository component, which is just going to act like PUSH and PULL data from your persistent medium (say database). Remember repository component never going to have any idea on business logic.
Once backend has been established, We can concentrate on my actual business process implementation. We can define one more level of Contract which defines all business operations which are to be done using Model classes. This interface has been implemented by BusinessLogic Component which does the core business activity (specific methods for every business operation). This particular component will use Repository component to delegate business data to persistence medium.
With above step completed, We can easily go and build Controllers. We should be calling business logic component methods in controllers and get work done. Once controllers are done, we can define our views and other UI elements like partial views etc.
Pictorial representation of the flow is as follows -
A simple architecture (from high to low level)
Presentation Layer
Domain Logic Layer
Data Access Layer
Database
Presentation layer is MVC project containing Views, Controllers and optional View-Models.
Domain Logic Layer is Class Library project which Presentation layer will access (via DLL or Service reference). This layer contains business logic and rules for the application.
Data Access Layer may contain two sub-layers-
Repository. User repository is best practice for any long term application.
Entity Framework Model.
This will communicate with database.
Database you already have.
I would suggest reading through a book by Scott Millet, called Professional ASP.NET Design Patterns.
ISBN : 0-470292-78-4
Scott walks through what a good ASP.NET site should look like from an architectural standpoint - i.e. DataAccess layers, Business Logic layers, Presentation Layers, Domain events etc.
By following on from industry standards, you will gain a better knowledge of how to correctly put together an MVC web-site.
Hope this helps.
I would suggest you to make your MVC application around a ASP.NET Web API , since it will help, in case you go for a mobile application later.
Since you are a MVC newbie, you should download some open source projects on MVC shared by seniors in the community. Study two or three projects, and analyze a solution which will the best for you.
A quick googling will get you to some good projects.
e.g.
Making a simple application , Prodinner
After that you should also go through MSDN tutorial on MVC 5 app with SSO , to enable social logins.

Guidelines on structuring code for .net projects

I generally use IoC pattern in my projects which are most of the time ASP.net based. Are there any guidelines on how to structure the projects in a general 3 layered project UI+BL+Data Access. I want to know more about how the folders should be created, where should constants be kept at within each layer (I keep all the strings such as query string parameters, stored procedure parameter etc in file named Constants which is singleton). How should I create classes that interact with Data Access layer from Business Layer etc. and all such code structure questions.
Is there any guidance or a book on this?
Microsoft has a plethora of information on this. I've used Microsoft .NET: Architecting Applications for the Enterprise as my bible for software architecture
http://www.amazon.com/Microsoft%C2%AE-NET-Architecting-Applications-Pro-Developer/dp/073562609X
Check out this MSDN guide as well
http://msdn.microsoft.com/en-us/library/ff647095.aspx
Also, take a look at some application frameworks like Sharp Architecture for examples
http://sharparchitecture.net/
A lot of NHibernate tutorials demonstrate software design principles that can be applied to any solution
http://nhforge.org/blogs/nhibernate/archive/2010/04/25/first-three-nhibernate-quickstart-tutorials-available.aspx
#robbymurphy has a great answer. I would only add that I keep most constants and interfaces in a separate project/assembly altogether. I call this my "core" assembly and and define interfaces that allow me to pass data from the top of the stack to the bottom without tightly coupling them.
It is not so much where they are used, but for what purose. I once attended a seminar class where the instructor pounded "high cohesion, low coupling" into our heads, over and over.
Keep those things that, in the real world, belong together, together, but, reduce dependencies between object whenever possible.
This is a cohesion question as well as a coupling issue: if the constants are truly internal to a class, make them private static members (i.e. and internal state enum) . If they are truly internal to a project, create a class for them, and make them internal (a database specific constant in your data layer). Otherwise, put them in a public class in their own project.

ASP.NET MVC3 Design Patterns and Proper Coding techniques

I recently worked at HP doing several ASP.NET MVC3 projects as I came from a software background I was relatively new to the inner workings of MVC3 as well as the best practices.
During this time I somewhat adapted the coding style of fellow co-workers and ways of designing my pages that I still stick with to this day. With all of this in mind my main question is what would anyone recommend for learning material; books/videos/tutorials. I can learn from any of those resources and I would love to know that I am coding properly.
I have several projects under my belt and many large scale business solutions that I have coded using Razor and ASP.NET but there are times where I feel that what I am doing is either very hacky or just an inefficient way of coding things. The larger the project is the more difficult it becomes to add new features because of this.
I think this is my lack of experience in coding but at the same time I would like to overcome this and I feel that with the mass experience I do have with MVC3 I could adapt to a easier style or design pattern that would help me not only optimize my code but become a much better web developer. If anyone has any suggestions on books or training sites or anything please let me know as I would love to get better.
Thanks in advance to anyone that has been in my shoes and is willing or capable of recommending anything!
I was dealing with the same issue and found it useful to make a mind map. While it's impossible to give you a full understanding, I can try point you in the right direction with some basic ideas.
download/view (http://www.xmind.net/share/highroad/mvc3-design-pattern/)
Are you familiar with design patterns? Well they exists with MVC applications too :)
If you want to talk the talk and understand what people including myself are talking about, you would need to know the typical design patterns that come with building what they call enterprise level applications. These design patterns are the only real way to begin to understand the concepts.
These patterns structure complex business logic in ways that have become the tried and tested solutions (design patterns) to the design challenges the developer's face.
In the diagram notice there are 3 main layers:
Presentation Layer
Business Logic Layer
Data Access Layer
Some of the highly used design patterns when dealing with Model View Controller in ASP.NET include:
Business Logic Layer Design Patterns:
Active Record. Models relate exactly to the database like in lightweight frameworks e.g. Ruby on Rails). When creating new MVC3 application with ASP.NET and scaffolding views and controllers, this is how it sets it up. Is perfect for less complex applications. So why not just use Ruby on Rails? I would
Domain Logic Layer. Uses MVC with the controller containing very little code and create lots of extra models that can do complex logic, the MVC is only for presentation. Often with this style of layer, a lightweight layer called a Service Layer can be used to call all the functions in the Domain Layer from the controllers i.e. the controller calls the method in the Service Layer class which calls the domain layer. This design pattern seems to be very popular with people who enjoy object oriented programming. See link below to my (quite basic) project designed using Domain layer.
Transaction Script - Use the controller to do a lot of the logic work per action, the problem is a lot of actions need to do the same things so there will be code repetition
For the Data Access Layer:
Something like entity framework models combined with a repository which can perform any SQL queries you need.
Not going into all the patterns for this layer but they include: Data Mapper
With simple apps, there is no real data access layer, it only becomes necessary if you use the Domain Layer in the business layer (which usually is the case)
Depending on what structure your application takes, your Models will mean very different things. In general they will not be models linked to the database (the default when creating a new app makes them like this). Instead they will be ViewModels which are only responsible for holding data that each of the views will need.
I have created a ssample app which you can see here.
https://github.com/testbrian/enterpriseframeworksB
I don't know if this is an example of an enterprise solution, but I have learned a lot from the techniques found in RaccoonBlog. I like how the Layout.cshtml and other razor files use RenderAction to modularize the views.
The project is an example of MVC3 using RavenDb, but it's also one of the best real world applications I've seen since it's actually used in production.
Hope this helps.

How to structure solution files and folders to fit best with MVP design-pattern?

Can you advice on structering the solution projects, files, fodlers in a way that it matches with the MVP design pattern in order to represent the pattern idea?
I mean how would you put your presenters, data acces layer, views etc.
Thanks
Solution architectures are generally pretty independent of which UI architecture you're using, although you might have some additional separation if you plan to have multiple UI applications (most projects don't).
I tend to start out with a template similar to this:
Acme.Sales or Acme.Sales.Core - internal domain/business logic
Acme.Sales.Entities - data entities used for persistence layers. Entities have similar class structure to the core (domain) model, but tend to have thinner logic, additional properties like Id, two-way relationships (as opposed to the one-way relationships in the domain model), and virtual members for the ORM to be able to override. This assembly will also normally include abstract repositories for CRUD operations on entities.
Acme.Sales.Entities.Impl where Impl is something like LinqToSql or NHibernate - this namespace defines one possible implementation for actually persisting the Entities. Concrete implementations of the abstract repositories go here.
Acme.Sales.UI contains common classes relating to any user interface - might be an MVP GUI or even a CLI. As with Entities, these are similar to the Core classes but tend to have presentation-specific logic and attributes, such as validation and formatting (which most often today is done through DataAnnotations). Note that the core library should also validate, but UI validation tends to be more about formatting and sanitization of inputs than business rules. It's tempting to mimic the domain's class structure here, but you'll have an easier time overall if you stick to flat, DTO-style classes for your UI model.
Acme.Sales.UI.Services contains abstract or concrete "service" types that are meant to interact with both the UI and the domain/persistence layers. Thus this project takes dependencies on Acme.Sales (domain), Acme.Sales.Entities (abstract repositories), as well as Acme.Sales.UI, and handles all of the mapping activities between those different layers.
Acme.Sales.UI.Impl where Impl here is something like Mvp, Mvc,Mvvm, and so on. You can drop the UI from this namespace if you want, as the implementation implies what it is. This generally takes a dependency on the UI project but adds those things specific to a particular UI model; controllers, presenters, view-models, etc. This is your actual "application". It's also where you normally choose an IoC container (AutoFac, Ninject, Spring.NET, Castle, Unity) and wire up all the specific implementations to the abstract types.
Within your application project you'd want to separate logical concepts into different sub-namespaces/folders. For example put your presenters in Presenters and views in Views - pretty straightforward - and create subdirectories in each of those if you start getting a really huge number of screens (e.g. Views.Billing and Views.Shipping). It's also OK to create top-level Area directories/namespaces here and put separate Presenters, Views, etc. in each one of those areas - this is the approach currently taken in ASP.NET MVC.
You don't need to separate Presenters and Views into different projects. Rest assured that the views which you tailor-made for MVP will be utterly useless for MVC or MVVM, and vice versa. The only part of a model-driven app that really stands a chance of being reused is the model itself.
Note that this is just a very basic architecture for an app with a single database and relatively simple domain logic. It doesn't include any higher-level back-end constructs like app integration (e.g. web services), eventing (pub/sub), batch processing, CQS, ad-hoc reporting, and so on and so forth. These tend to be pretty common in larger-scale business apps but if you're just starting out on a new social bookmarking app then you don't need any of that complexity.
Also note: This is all assuming you're planning at least a medium-size project - let's say one that you and/or your team will be working on for 6 months or more. If you plan to bang it all out in 1 month or less then please, don't waste your time on solution architectures at all. It's perfectly OK to just jam it all into one project and reuse the same classes for domain, entities, and UI - as long as the project is small enough to be easily understood and maintained. Carefully monitor the complexity and maintenance overhead and consider refactoring into the above structure over a longer period of time if the project starts turning into a ball of mud.
Below would be a nice start. You could split up even more if the project gets bigger:
Company.Project.Core -> Controller logic
Company.Project.Domain -> Domain models (view models and database models)
Company.Project.Interface -> Views, presenters

Asp.Net MVC and Entity Framework Architecture

I'm working on a fairly large project at the moment and am currently in the planning stages. I've done a lot of reading into the various patterns suggested for development, somthing that has split the team at the moment is when using Entity Framework should the classes be passed through the applciation layers so that a view accepts an Entity Framework class or should these classes be mapped to BLL Classes and if so at which point (Controller or Library) should this be done?
I'm interested in hearing some positives and negitives for each solutions.
This is one of those great "it depends" questions ....
For me it's a matter of pragmatism. I use the raw entity classes where ever I can for expediency. I start using DTOs when either the object graph in question starts becoming too cumbersome or the object in question has sensitive data I don't want sent over the wire.
This is again one of those questions that doesn't really have a right or wrong answer, its personal taste really. Personally I would opt for using DTO's or interfaces when passing data to the Views. I don't tend to pass around entity objects to different layers of my application they are strictly confined to the DAL, or if I do need to pass it up a layer I would almost always use an interface never the concrete type.

Resources