I am developing an application using MVC3 and Entity Framework. Its a three layered approach with Presentation Layer hosted in Web Server and Business Layer and Data Access Layer in Application Server. We are not exposing the Object Context to Presentation Layer or Business Layer. Object Context is wrapped in Data Access Layer only and exposing data access and data persistence as functionalities as Data Access Layer methods(ie data access logic is separated and implemented in Data Access Layer only). Business Layer is calling data access layer methods and returns data to Presentation Layer.
My concern is most of the Business Layer Methods are for just to access the data and it is just forwarding the call to Data Access Layer without any operation. So we are repeating the code in both layers. Do we have any other better approach to avoid this duplication.
Is it a good practise to implement the data access logic in the business layer in Layered approach?
Can someone suggest a good implementation approach for Layered application with 3-tier architecture?
If you find yourself that all that your business layer is doing is simply delegating the calls to the data access layer then this is a strong indication that this business layer is probably not necessary for your application as it brings no additional value. You can get rid of it and have the controllers talk directly to the data access layer (via an abstraction of course) - that's what most of the tutorials out there show with the EF data context.
In simple applications that are consisting mainly of CRUD actions, a business layer might not be necessary. As your application grows in complexity you might decide to introduce it later, but don't do too many abstractions from the beginning especially if those abstractions don't bring you any additional value.
As previously mentioned there is no "right" way to set things up. I have found a few things over the years that help me decide which approach to take.
Two-Tiered
If your shop is stored procedure heavy with a lot of database programmers and tends to put business logic in the database then go with a two-tiered approach. In this situation you will find that your business layer is generally just calling the data layer. Also, If your code base and pages tend to be small and you never repeat functionality then go with a two tiered approach. You will save a lot of time.
Three-Tiered
If your shop likes to have a lot of business logic in code and that logic is repeated everywhere then go with three-tiered. Even if you notice a lot of your business layer just calling the data layer you will find over time when you add functionality that it is a whole lot easier to just add code to the business layer. Also, If you have a large code base with a ton of pages with a lot of repeated logic then I would definitely go with this approach.
I have found a mixture of both in our enterprise level application at my work. The problematic areas are the ones where dynamic sql (gag) was used and business logic was repeated over and over. I'm finding as I refactor I pull this code into a 3-tiered architecture and save myself a ton of time in the future because I can just reuse it.
I don't think its necessarily bad to duplicate the code for logical separation. Time will come when this will pay off. Say you will replace SQL server by Oracle. Or Microsoft will come up with Linq 2.0 and some implementations will change. You will be thanking yourself for having it separate, while those who called database right from the business layer will have to do modifications in both places - DAL and BLL.
For what its worth. But again, there's no right answer, up to utility, usability, convenience, and most importantly having it matching its purpose.
Hope this is of help.
Related
I've been struggling with a design decision and was hoping for some feedback.
Architecture summary:
ASP.NET MVC WebAPI solution with a SPA frontend written in KnockoutJS and Entity Framework hooked up to a SQL DB.
The problem: we have two entities that pull a value (Rate) from a somewhat complex lookup table. The lookup table filters down to a distinct option based on 5 parameters, all 5 parameter values can be determined based on properties on each entity or a related table. On top of this look up value, both entities can have "Rate Modifiers" which can add another small amount to this lookup value.
The question: where should we put this lookup logic if we would like this calculated rate to be available anytime we use these two entities?
Service layer: have a service to request these entities, request
the entities from the Data (Infrastructure) layer repository, then
make individual calls back to the data layer to get the computed
rate
Data layer: inside the data layer repository get all the
entities and lookup the values there within the repository
UI layer: just send the entities to the UI layer and then have web
services to retrieve the rates for the 5 parameters
DB: Create a view in the db for these entities that does all the
rate lookup logic for us in the db
Other suggestions?
I see advantages and disadvantages to all of these options and none of them feel quite right to me. Option 3 feels like it's the cleanest, but is probably the least performant and is the most chatty. options 2/4 seem messy putting business-like logic in the data layer and option 1 feels a little over complex and inefficient.
Any insight would be greatly appreciated! Thank you.
If seperation of concerns or keeping everything clean is your concern, then it is best to keep it in the Service layer. Just as you suggested ,having the UI layer call the service layer which in turn calls the datalayer. The service layer is where the business logic usually lies. This is the ideal situation though.
However, if speed is your concern I think it is better to keep things in the DB layer probably as a stored procedure. In my experience this performs really well. But generally it is best not to spread business logic across layers.
Whatever solution you use , it is best to choose based on what your priority is - seperation of concerns or speed ,etc.
Do let us know what you went with.
This question already has answers here:
Is the Controller in MVC considered an application service for DDD?
(4 answers)
Closed 6 years ago.
In an ASP.NET MVC world, could controllers act as the application layer, calling into my domain objects and services to get the work done (assuming the controllers just strictly calls the domain and does nothing more). In the particular case that am dealing there is very minimal application flow logic that I need to model, hence am thinking about doing away with application layer and calling the domain directly from within the controller.
Is this a fair approach?
I guess what you mean here is that your business logic is implemented using the Domain Model pattern. In such case, you application layer should be very simple, and by definition it shouldn't host any business logic. All business logic should reside in the domain layer; methods in your application layer should resemble the following steps:
Load instance of an aggregate
Execute action
Persist the updated aggregate
Return response to the user
If that's all you do in your application layer, I see no reason not to put it in the controller.
If, on the other hand, your domain model is anemic, and you do have business logic in the application layer, then I'd prefer to introduce a separate layer.
Treating your MVC controllers as your DDD application layer will present a few negative situations.
The biggest one is that your application layer (regarding DDD), is one of the key places where you model your domain/business processes. For example, you might in an application service have a method called:
PayrollService.CalculatePayslips();
This might involve, checking a domain service or external system for the current active employees, it might then need to query another domain service or external system for absences, pension deductions, etc. It will then need to call a domain service (or entity) to do the calculations.
Capturing domain/business logic like this in the MVC controllers would cause an architectural issue, should you want to trigger the task of calculating payslips from elsewhere in the system. Also if you ever wanted to expose this process as a web service, or even from another MVC controller, you would have references going across or up into your presentation layer. Solutions like these "might work", but they will contribute towards your application becoming Spaghetti Code or a Big Ball of Mud (both code smells in an architectural sense). You risk causing circular references and highly coupled code, which increases maintenance costs (both time, money, developer sanity, etc.) in the future.
At the end of the day, software development is a game of trade-offs. Architectural concerns become bigger issues, the bigger your application grows. For a lot of very small CRUD apps, architectural concerns are probably negligible. One of the key goals of DDD is to tackle complexity, so it could be argued that most DDD projects should be of sufficient complexity to be concerned about good enterprise architecture principles.
I would not do it.
The effort of creating a separate class for the application service and then invoke it from the controller is minimal. The cost is also only there when you build the application.
However, the price you have to pay once you start to maintain the application is much higher due to the high coupling between the business layer and the presentation layer.
Testing, reuse, refactoring etc is so much lower when you make sure to separate different concerns in an application.
I'm new to asp.net MVC and EF, so excuse me if my question is not clear or easy.
I have read some tutorials about EF Code-First approach and now I'm trying this tutorial Getting Started with EF using MVC.
Using Code-First approach I'm using the POCO classes to define my DB model, DB logic, DB validation, UI validation and some UI logic. So I can use these classes(or objects) in my presentation layer or use them as JSON objects when dealing with Web-Services(or in JavaScript code).
My question: Isn't that mixing some logic together? I mean shouldn't I use like special view-model classes for presentation and these classes should have the UI logic and validation ?!
Is it good practice to send the POCO object to the view(or to the client in general) ?
Finally i need some guidance on how to organize my project layers or folders? I see many ways and I'm confused about what to choose or what format I should base my own on?!!
You should not use your data entities in higher layers of your application. Transform/compose/copy data from DAL into view model or business classes using a library like Automapper. This keeps the layers of your application independent and hides your database schema from end users.
Keep in mind that MVC is only concerned with presentation, all real work should happen in other layers of your app. I try to keep layers independent and use a little bit of glue code to bundle them into an app. I may write data access and business logic layers when working on MVC project, but then re-use in a command line utility. There are a lot of books that talk about writing quality code. I personally found Clean Code, Code Complete 2, and Design Patterns extremely helpful.
As LeffeBrune said, is bad practice to show directly your data entities to the presentation layer, you can try to expose some interfaces in form of project services that return the view model to the controller. This can help to keep the layers separate, and implement Unit of Work pattern and some other cool stuff.
You can start reading the Scott Millet Book
ASP.NET Design Patterns
for a starting point in designing a good layered application, here his blog.
You can define interfaces in your business layer which your EF entities can implement; the business logic doesn't know about the actual implementation. To do this you need the data layer to reference the business layer which means you're inverting the dependencies - you then use an IoC container to bind the interfaces to their implementations. ...but yeah that's one of many, many ways to go about it.
The thing is, with single responsibility in mind, your entities shouldn't worry about UI stuff - this can mean your interfaces also need to be implemented by "view model" classes, which implement things like validation and other business & presentation concerns.
Your questions require a lot of discussions.
Choosing infrastructure for your project is a complicated issue that depends on lots of factors. There are some design patterns that address different requirements in a project which involve you or your team in multiple concepts and technologies. I recommend you two valuable resources that help you understanding software architecture focused on .Net technologies.
CSLA.NET : The CSLA .NET framework is an application development framework that reduces the cost of building and maintaining applications. Rockford Lhotka, createor of CSLA.NET, has some books that deeply describe an optimal infrastructure of a project; all of your questions have answered in his books.
Microsoft Spain - Domain Oriented N-Layered .NET 4.0 Sample App: the project/sample is willfully restricted to .NET implementation of most used patterns in N-Layered Domain Oriented Architectures based on simple scenarios easy to understand (Customers, Orders, Bank Transfers, etc.). The project/sample is very well documented and all of your questions , also, have answered in the project.
All in all, view-models, POCOs, layers, etc. are concepts that have root in software architecture and I believe that they can not be described in short.
What I normally use is a POCO layer to use in my data access and a view model layer to use in my views just as LeffeBrune said.
All my layers use POCOs and the controllers are responsible to construct the view model that each view needs.
To get this work more automated I use automapper.
So my solution structure gets usually to be like this:
Model (POCO)
Data access (NHibertante)
Service (Business Layer)
Web (UI)
ViewModel
I am looking for some guidance on how to incorporate business rules into an asp.net mvc application and how they relate to the model.
First a little background so we know what kind of solutions are relative for this question. At work we use WinForms, MVP, BusinessObjects, DataAccessObjects, and DataTransferObjects. The boundaries of the layers use DTOs to send parameters to methods and as return types, or return List types.
Right now we are adding a facade layer to translate the DTOs into Domain Objects for the UI to work with, since the architect does not like how using DTOs in the PresentationLayer is working currently. I am comfortable about all of this in theory aside from it being practical or not.
I am making a website for fun, but for considerations lets say it serves the same amount of traffic as SO, something like 60,000 hits a month last I heard. I am comfortable with the mechanics of the controllers and the views, and how the model integrates with the two.
I am using NerdDinner as a sample for building the site and I follow the Repository pattern implementation in the examples. What I don't get is how to incorporate business objects into the mix.
I hear people talk about LINQ as the DataAccessLayer/DataAccessObjects. If I force all of my requests though the business objects as I am used to I have introduced some weird dependencies. Both my UI and my BO have to know about my DAO.
What would kind of make sense is to use the LINQ classes as a true DAO layer, hide it behind the BO, and have the BO transform between POCO and LINQ objects.
My only concern there is I am fine with binding my UI to LINQ classes, and don't really need all the extra work, I am happy with a thin lightweight approach as in NerdDinner.
So what I have essentially is the Repository that is instantiated in the controllers that takes and return LINQ objects. My business objects have static methods that just take LINQ classes and perform some calculation, say apply a certain states tax %, or w/e.
Since a lot of these calculations have to be done across the results of the repository I am thinking of combining them into one central area, like a facade layer, but one that just does transforms against the data and not translating to other objects sets (DomainObjects <-> DTOs).
Should I do that, or should I say that those business methods really are part of my model and that they should be in the repository methods that return the objects?
From a design standpoint I would design it like this. Of course naming is just for the purpose of this post you don't have to name your DAL and BLL ..Repository and ..Service.
Have repositories (or one) where your data access/queries should be happening. It should ideally just contain queries (compiled or not). I personally have a repository for each data type to help keep queries separated.
The next layer should be your business layer which I like to call services. These classes are responsible for all logic regarding validation, prep steps and anything else needed to be done to get the consumer of the service the information it needs. As with an ASP.NET MVC app I have my services return view models which are then directly passed into strongly-typed views. With my services I usually group them logically together instead of one for each data type.
This is a great design because it keeps your data access code and presentation code nice and thin and most of the logic where things can go wrong is in your service (or business) layer.
This is a general question about design. What's the best way to communicate between your business layer and presentation layer? We currently have a object that get pass into our business layer and the services reads the info from the object and sets the result into the object. When the service are finish, we'll have a object populated with result from business layer and then the UI can display according to the result of the object.
Is this the best approach? What other approach are out there?
Domain Driven Design books (the quickly version is freely avaible here) can give you insights into this.
In a nutshell, they suggest the following approach: the model objects transverse from model tier to view tier seamlessly (this can be tricky if you are using static typed languages or different languages on clinet/server, but it is trivial on dynamic ones). Also, services should only be used to perform action that do not belong to the model objects themselves (or when you have an action that involves lots of model objects).
Also, business logic should be put into model tier (entities, services, values objects), in order to prevent the famous anemic domain model anti pattern.
This is another approach. If it suits you, it depends a lot on the team, how much was code written, how much test coverage you have, how long the project is, if your team is agile or not, and so on. Domain Driven Design quickly discusses it even further, and any decision would be far less risky if you at least skim over it first (getting the original book from Eric Evans will help if you choose to delve further).
We use a listener pattern, and have events in the business layer send information to the presentation layer.
It depends on your architecture.
Some people structure their code all in the same exe or dll and follow a standard n-tier architecture.
Others might split it out so that their services are all web services instead of just standard classes. The benefit to this is re-usable business logic installed in one place within your physical infrastructure. So single changes apply accross all applications.
Software as a service and cloud computing are becoming the platform where things are moving towards. Amazons Elastic cloud, Microsofts Azure and other cloud providers are all offering numerous services which may affect your decisions for architecture.
One I'm about to use is
Silverlight UI
WCF Services - business logic here
NHibernate data access
Sql Server Database
We're only going to allow the layers of the application to talk via interfaces so that we can progress upto Azure cloud services once it becomes more mature.