ASP WebApi : Service layer, business layer and data access layer - model-view-controller

If I need to write a simple webapi which need to get/create/update/delete of the products. Is this really need a business layer.
I am using Entity Framework which I understand this is similar to Repository Pattern.
If my webapi application is very simple which not much complex business logic e.g. bank reconciliation etc
Do i really need to have a business logic layer? Can i just have a service layer which create products / remove the products etc..

No, it is not necessary at all to have a business layer! (with a disclaimer)
Let me support my argument and address your concern
One of the most basic design principles of software engineering is KISS. If you feel the business problem you are solving is pretty simple then why to make code complex by introducing unnecessary layers.
Not having the 'business layer' is not a crime. It is well supported by the community as well that's why in one of the community and industry loved framework Spring there is a module called spring-data-rest exactly supporting design you are proposing (simple code with business layer and on top without explicit web layer)
The last argument evolutionary approach. With the increasing complexity of system and technology community released that system and code complexity should be evolved (thought process every well explained here). Don't try to think about future today (again referring to another basic design principle YAGNI). (Explaining disclaimer here) So start from simple and if in future you felt the need of having separate business logic layer because you got to write some actual business solving code then introduce that layer and evolve it!

Related

Repository pattern and web api

Hi i learned web api 2 recently and i am working on a sample project now.I am following layered architecture in my project.This is the flow
controller=>Business Layer=>Data Layer
Now i read some article about the repository pattern which sound better nowadays.
i saw the flow like
controller=>services=>repository
Is there any significant difference between the two flows?
As a beginner which style of architecture should i flow?
Can someone help me to understand these patterns?
When you use services with repository you should make it generic and use Unit of Work (UOW) so you don't repeat yourself with CRUD actions on every entity. Then add some object relational mapper (ORM) like Entity Framework. It is prefered that you also use domain objects for storing your logic there, and make the services return data transfer objects (DTO), because best practice is to keep your services small and clean. Then you also need to include some mapping tool/logic to map DTO to Domain objects.
And you see where this is all going. Suddenly you have far more complexity and obstructions than you need. Because only one thing that customer care about is quality of your product not some fancy architecture.
But as project grow it is much more important to have proper architecture, automatic tests etc. , so it is valid in large projects. If you want to experiment and learn it is great opportunity, but if you have running application in production, i would rather not make that big changes.
TLDR: they are both valid

Best Practices when Migrating to Microservices

To anyone with real world experience breaking a monolith into separate modules and services.
I am asking this question having already read the MonolithFirst blog entry by Martin Fowler. When taking a monolith and breaking it into microservices the "size" element of the equation is the one that I ponder over the most. Specifically, how to approach breaking a monolith application (we're talking 2001: A Space Oddessy; as in it is that old and that large) into micro services without getting overly fine grained or staying too monolithic. The end goal is creating separate modules that can be upgraded indepenently and scaled independently.
What are some recommended best practices based on personal experience of breaking a monolith into microservices?
The rule of thumb is breaking the monolith based on bounded context . The most common way of defining the bounded context is using BU ( Business Unit) . For example the module which does actual payment is mostly a separate BU .
The second thing to consider is the overhead micro-services bring. You should analyse the hardware , monitoring , infra pieces before completely breaking the service. What I have seen is people taking smaller microservices out of monolith instead of going and writing say 10 new service and depreciating the monolith.
My advice will be have an incremental approach . Take the first BU which is being worked upon out of monolith. This will also give a goos learning curve for the whole team.
You should clearly distinguish sub-domain areas (bounded contexts) from you domain.
Usually (if everything is fine with your architecture) you already have some separate components in your monolith application which responsible for each sub-domain. These components interact with each other in one process
(in monolith application) and you should to think about how to put them into separate processes. Of course you need to produce a lot of refactoring when moving one by one parts of the monolith to microservices.
Always remember that every microservice is responsible for some sub-domain.
I strongly recommend you to learn Domain Driven Design.
Domain-Driven Design: Tackling Complexity in the Heart of Software by Eric Evans
Implementing Domain-Driven Design by Vaughn Vernon
Also learn CQRS pattern
At the beginning you also should decide how your micservices will interact with each other.
There are several options:
Direct calls from one service to another
Send messages through some dispatcher service
which abstracts the client service from the knowledge where the called (destination) services are located.
This approach is similar to how proxy server like NGINX works.
Interact through some messaging bus (middleware), like RabbitMQ
You can combine these options, for example Query requests can be processed through Dispatcher Service, Commands and Events through message bus.
From my experience the biggest problem will be to go away from a single database,
which monolith applications is usually used.
In addition some good practices:
Put each microservice in own repository - this isolates from the ability to directly use the code of one micro service in another.
You also get faster checkouts and builds of each microservice on CI.
Interactions with any service should occur only through its public contracts.
It is necessary to aspire that each microservice has its own database
Example of the sub-domains (bounded contexts) for some Tourism Industry application.
Each bounded context can be serviced by a microservice.
We also started our journey some time back and i started writing a blog series for exactly the same thing: https://dzone.com/articles/how-i-started-my-journey-in-micro-services-and-how
Basically what i understood is to break my problem in diff. microservices, i need a design framework which Domain Driven Design gives(Domain Driven Design Distilled Book by Vaugh Vernon).
Then to implement the design (using CQRS and Event Sourcing and ...) i need a framework which provides all the above support.
I found Lagom good for this.(Eventuate , Spring Microservices are some other choices).
Sample Microservices Domain analysis using Domain Driven Design by Microsoft: https://learn.microsoft.com/en-us/azure/architecture/microservices/domain-analysis
One more analysis is: http://cqrs.nu/tutorial/cs/01-design
After reading on Domain Driven Design i think lagom and above links will help you to build a end to end application. If still any doubts , please raise :)

MVC - are there situations when it's either irrelevant or inappropriate?

When developing an app with GUI, and database access, are there situations where the MVC architecture isn't relevant?
To me it seems that the Views and Controllers must only be different entities is one to upgrade the views, or to replace them with something else, namely mobile displays (or predicts such a possible change for the future of the app).
Also, I see the separation of the Model and Controllers only necessary if the Model is to be upgraded / replaced.
So is there any other purpose for the MVC architecture that the situations when components should be upgraded/ changed, or is this really it?
I like MVC because it makes it easier to think about how different parts of the app are going to work together. If everything is just lumped in together, I find it much harder to visualise in my head.
So it's not really a case of when you should use it, rather how do you prefer to think?
If you find it easier not using MVC then you should probably not use MVC.
I think, the root of you confusion is the scope at which you try to apply MVC design pattern.
MVC is not a pattern for small applications. Instead you are supposed to apply it, when your free-form OOP code starts to become unmanageable. Your codebase might be implementing all of the SOLID principles, but at some point you will start getting lost there.
That would be when you should be using MVC, because this design pattern applies additional constraints. It does not add anything new to application. Instead it limits what code can go in what parts of your application.
P.S. you also seem mistaken about what separation there is in MVC. The basic divide is between model layers and presentation layers. Those are two main parts MVC applications. And only then withing the presentation layer there is a separation between views and controllers. You might benefit from reading this article.
For me, it all comes down to testability. Automated testing of UI code is exorbitantly expensive compared to testing of model code. It is much easier to achieve test coverage in model and event controller layers compared to view layers.
If you have no need to test your application, and it is small enough that you can keep it all straight in your head, then MVC is probably a waste of time. Very few applications are truly small enough that these concerns are not at issue. But if the app is truly that small, MVC will add far more overhead than it will provide in value.
Don't think of MVC design pattern as you business architecture. Treat MVC as presentation architecture. There are many arguments about MVC usage in terms of business architecture. This stackoverflow question is one example.
Actually, you are looking for N-Tier architecture. Where it is separated as DAL, BLL and PL:
Data Access Layer (DAL):
A layer responsible to inteact with the Storage (insert/update/delete)
BLL:
A layer where the business logic resides. This layer is the core of your application. Some people often use the term Middleware (please correct me if wrong) to represent the BLL. BLL does not know the UI, means that it can be used by Desktop app, web app, mobile app, etc.
PL:
This is your presentation layer or UI layer. MVC, at least the View and Controller resides here.
There are benefits to the MVC architecture, and there are some disadvantages to it. You have to weigh them for your project to see which would be the most appropriate for you.
Advantages for MVC:
More maintainable because it's compartmentalized (separation of
concerns).
It's more testable because you can unit test the controllers.
You typically have more control over the HTML that gets generated
(Yes, you can accomplish the same with webforms, but only if you give
up all of the advantages of webforms as well).
Your webpages will be smaller and faster because you won't be
carrying around page/view/control state.
Integrates better with client-side lifestyle and libraries
(Bootstrap, jQuery and it's many plug-ins, AJAX, etc)
Advantages of webforms:
More 3rd party controls (webforms relies heavily on either 3rd party controls, or custom usercontrols to achieve rapid application development).
If you need viewstate, then it takes less work, but this is pretty
rare if designed right.
Integrates better with server side control libraries.
Of course, someone is going to say, why did you list xyz as an advantage for whatever, because you can do that in the other one too! Well, you can achieve the same thing in both frameworks, it's just a matter of ease. What is easy for one may be more difficult in the other, but both of them, given enough time and resources can do it too.
MVC is about separation of concerns and making these concerns testable.
Someone said 'MVC is not a pattern for small applications.'. I disagree. Why? It only dictates how you separate concerns, I don't understand why this should be different for small applications. I would argue it's even simpler because every developer uses the same pattern and is used to it. It's not overhead, it's consistency. Also look what this guy has to say.
Another thing: MVC is a presentation layer pattern (Separated Presentation), it means it logically separates your UI in a models, views and controllers. Controllers are responsible for managing the flow, interacting with the backend system to query and save data, and converting that data to models (or view models) that are used by the views.
The backend in itself is another system, which has its own independent architecture, with services, domain and data layer (as for example the onion architecture, of which an example can be found here).

Linq to SQL layers/architecture?

I am sorry for my question may looking a old repetitive questions but I as I am starting Linq to SQL I want to discuss how many layers (architecture) should I use ?
I am working on web mostly web sites and small to medium scale web applications. I understand dividing application into layers help its maintainanace and enhancement but frankly I want some balance way which give me rapid development and code reuse-ability as well. I cannot spare so much time on unwanted management of layers.
Before I was using 4 layers (business objects, BLL,DAL and user itnerface.) I became confuse on it as different people have described different layers. Please guide me what and how many layers I should use ? Thanks
Don't use the layer architecture. Use the onion architecture.
The most important aspect from architecture perspective is the separation of concerns. Separation of concerns leads to clean code, easy maintenance, extensible, etc. That said, I recommend to base your decisions based on the following criteria:
Try to architect your system in a loosely coupled way. Use messaging instead of RPC as messaging is reliable, scalable, asychronous, loosely coupled, etc. You can either use MSMQ or NServiceBus (for service bus based architecture).
Create layers based on the separation of concerns concept. For e.g. you can go for typical 3 layered architecture which will have just UI layer, business logic layer (business rules+workflow) and data access layer or more granular such as UI layer, services layer (facade), business logic layer, data access layer, etc. Using IoC / Dependency injection will make life easy as none of the layers will have direct dependency. Moreover, it promotes unit testing easy as you inject mocks instead of the real implementations for the unit test. There are so many IoC frameworks available (NInject, Autofac, Castle Windsor, Structure Map, etc...)
Try to use EF instead of Linq to SQL as the later works only with SQL, while the EF works with any database. Moreover, in my opinion, EF is where microsoft is innovating and I would assume that Linq to SQL may be retired one day.
Great question haansi. This is something that I have wrestled with quite often when building small to medium sized sites. Finding that balance of creating a architecture that gives you the greatest flexibility and allows for rapid deployment is what I think we all need to strive for in all of our work.
With that being said, I have found that using the Repository Pattern to be quite helpful with LINQ to SQL projects. I couple that with the Model View Presenter pattern (for WebForms or other projects) and it provides a great foundation for reuse with minimal layers.
My Webform calls a Presenter class, which in turn is responsible for populating the View. To populate that View the Presenter can call N number of Repositories. The Repository is where you encapsulate your DataContext class and your LINQ to SQL calls. These calls return the model classes.
One huge benefit to this regardless of the size of the app is that get great re-use out of your Repository, you get to maximize the use of LINQ and you have used some patterns that other software developers could easily read and support.
Another big benefit is that you now have created a simple architecture that can benefit from using Unit Testing to test from the Presenter back to the Repository without a ton of effort.
Good luck!
I decided to use one layer (DAL + BLL) for small projects and for large applications will use Different layers for DAL & BLL. I will use Linq in DAL and funtiosn will return IQueryable.

Strategies for sharing common business logic across different programming languages

Having a monolithic business application with complex business logic implemented in Visual Dataflex, we are facing the challenge of maintaining our business logic across programming languages as certain features are written in other programming languages (mainly .NET).
So I am looking for strategies to "synchronize" business logic across different programming language implementations, in order to avoid mismatches. Avoiding duplication is a plus, but this may be compensated by automated testing.
EDIT: SOA is a great suggestion. But what about those cases where a service will not be fast enough?
EDIT 2: Any suggestions for using a metalanguage?
Looks like you're looking for Service Oriented Architecture (SOA). With SOA, you can define your business logic as Services, which can be called from any program, in any language. When the business logic changes, change your Service and the behavior will change in everything that uses it. SOA also minimizes code duplication, because the logic only appears in one place (the service).

Resources