Architectural Issue in ASP.Net application with Web API - asp.net

We have an 3 layer architecture of ASP.Net application which builds with SQL back end and running in Production for last 2 years.
Now we plan to start develop Version 2 of that application by expose data through Web-API. So, we are busy creating the POC for that architectural implementation.
Problem is, we have an existing solution with 3 projects(ASP.NET+BAL+DAL). So, I planned to replace DAL with Web-API because it itself contains Models to interact with back end Database.
I have created a separate solution for Web-API. In my POC, Web-API runs in separate port(ex:localhost:122) & My ASP.NET application runs in with default port(ex:localhost:80). From my ASP.NET application, while I call the Web-API controllers its not returning results. But while checking the Web-API like "http://localhost:122/api/Products" i'm getting the responses.
While seeing the sample Architectures from google, People introduce "Service Layer" in the main(ASP.NET+BAL+ServiceLayer) solution and keep calling that service layer will internally call the original(withich connects with DB) Web-API. Is that only way of doing it ?
Please correct me if my assumptions are wrong.

When exposing a Web API, it is best to think of it like an alternate UI. It just so happens that it is a very ugly UI (proabably JSON or XML). And it isn't very usable by average users because they would have to construct requests by hand etc.
A 3 Tier architecture is about preserving the BAL and DAL for multiple front ends. Web API is an alternate front end. So, it would seem best to reference BAL and DAL inside a new process (the Web API) and then expose it.
I'm not sure if this is the same concept as a "Service Layer" or not. That term is overloaded with many different meanings to different people.
So, I would not replace the DAL with the Web API (because it has models etc). Instead, use the Web API models (or view models) to define the alternate front end structure and map to these from existing BAL services and entities.
Hope this helps.

Related

how to wire-in domain event handlers in multi-layer applications

So my question is very much related to this one: Entity persitance inside Domain Events using a repository and Entity Framework?
EDIT: A much better discussion on the topic is also here: Where to raise persistence-dependent domain events - service, repository, or UI?
However my question is rather more simple and technical, assuming that I'm taking the right approach.
Let's suppose I have the following projects:
MyDomainLayer -> very simple classes, Persitence Ignorance, a.k.a POCOs
MyInfrastructureLayer -> includes code for repositories, Entity Framework
MyApplicationLayer -> includes ASP.Net MVC controllers
MyServicesLayer -> WCF-related code
MyWebApplication -> ASP.Net MVC (Views, Scripts, etc)
When an event is raised (for example a group membership has been granted),
then two things should be done (in two different layers):
To Persist data (insert a new group membership record in the DB)
To Create a notification for the involved users (UI related)
I'll take a simple example of the last reference I wrote in the introduction:
The domain layer has the following code:
public void ChangeStatus(OrderStatus status)
{
// change status
this.Status = status;
DomainEvent.Raise(new OrderStatusChanged { OrderId = Id, Status = status });
}
Let's assume the vent handler is in MyApplicationLayer (to be able to talk to the Services Layer).
It has the following code:
DomainEvent.Register<OrderStatusChanged>(x => orderStatusChanged = x);
How does the wire-in happen? I guess is with structuremap, but how does this wire-in code looks exactly?
First, your layering isn't exactly right. Corrections:
Application Layer - ASP.NET MVC controllers are normally thought of as forming an adapter between your application layer and HTTP/HTML. Therefore, the controllers aren't themselves part of the application layer. What belongs in application layer are application services.
MyServicesLayer - WCF-related code. WCF implemented services are adapters in the hexagonal architecture referenced by Dennis Traub.
MyWebApplication - ASP.Net MVC (Views, Scripts, etc). Again, this forms an adapter in a hexagonal architecture. MVC controllers belong here as well - effectively they are implementation detail of this adapter. This layer is very similar to service layer implemented with WCF.
Next, you describe 2 things that should happen in response to an event. Persistence is usually achieved with committing a unit of work within a a transaction, not as a handler in response to an event. Also, notifications should be made after persistence is complete, or in other words after the transaction is committed. This is best done in an eventually consistent manner that is outside of the unit of work that generated the domain event in the first place.
For specifics on how to implement a domain event pub/sub system take a look here.
My first recommendation, get rid of the notion of Layers and make yourself familiar with the concept of a Hexagonal Architecture a.k.a. Ports and Adapters.
With this approach it is much easier to understand how the domain model can stay independent of any of the surrounding concerns. Basically that is object-orientation on an architectural level. Layers are procedural.
For your specific problem, you might create a project containing the event handlers that project events into the database. These handlers can have direct access to the database or go through an ORM. You probably won't need any repositories there since the events should contain all information that's needed.

Should the services in my service layer live in separate projects/DLLs/assemblies?

I have an ASP.NET MVC 3 application that I am currently working on. I am implementing a service layer, which contains the business logic, and which is utilized by the controllers. The services themselves utilize repositories for data access, and the repositories use entity framework to talk to the database.
So top to bottom is: Controller > Service Layer > Repository (each service layer depends on a single injectable repository) > Entity Framework > Single Database.
I am finding myself making items such as UserService, EventService, PaymentService, etc.
In the service layer, I'll have functions such as:
ChargePaymentCard(int cardId, decimal amount) (part of
PaymentService)
ActivateEvent(int eventId) (part of EventService)
SendValidationEmail(int userId) (part of UserService)
Also, as an example of a second place I am using this, I have another simple console application that runs as a scheduled task, which utilizes one of these services. There is also an upcoming second web application that will need to use multiple of these services.
Further, I would like to keep us open to splitting things up (such as our single database) and to moving to a service-oriented architecture down the road, and breaking some of these out into web services (conceivably even to be used by non-.NET apps some day). I've been keeping my eyes open for steps that might make make the leap to SOA less painful down the road.
I have started down the path of creating a separate assembly (DLL) for each service, but am wondering if I have started down the wrong path. I'm trying to be flexible and keep things loosely coupled, but is this path helping me any (towards SOA or in general), or just adding complexity? Should I instead by creating a single assembly/dll, containing my entire service layer, and use that single assembly wherever any services need to be used?
I'm not sure the implications of the path(s) I'm starting down, so any help on this would be appreciated!
IMO - answer is it depends on a lot of factors of your application.
Assuming that you are building a non-trivial application (i.e. is not a college/hobby project to learn SOA):
User Service / Event Service / Payment Service
-- Create its own DLL & expose it as a WCF service if there are more than one applications using this service and if it is too much risk to share the DLL to different application
-- These services should not have inter-dependencies between each other & should focus on their individual area
-- Note: these services might share some common services like logging, authentication, data access etc.
Create a Composition Service
-- This service will do the composition of calls across all the other service
-- For example: if you have an Order placed & the business flow is that Order Placed > Confirm User Exists (User Service) > Raise an OrderPlaced event (Event Service) > Confirm Payment (Payment Service)
-- All such composition of service calls can be handled in this layer
-- Again, depending on the environment, you might choose to expose this service as its own DLL and/or expose it as a WCF
-- Note: this is the only service which will share the references to other services & will be the single point of composition
Now - with this layout - you will have options to call a service directly, if you want to interact with that service alone & you will need to call the composition service if you need a business work flow where different services need to be composed to complete the transaction.
As a starting point, I would recommend that you go through any of the books on SOA architecture - it will help clear a lot of concepts.
I tried to be as short as possible to keep this answer meaningful, there are tons of ways of doing the same thing, this is just one of the possible ways.
HTH.
Having one DLL per service sounds like a bad idea. According to Microsoft, you'd want to have one large assembly over multiple smaller ones due to performance implications (from here via this post).
I would split your base or core services into a separate project and keep most (if not all) services in it. Depending on your needs you may have services that only make sense in the context of a web project or a console app and not anywhere else. Those services should not be part of the "core" service layer and should reside in their appropriate projects.
It is better to separate the services from the consumers. In our peojects we have two levels of separation. We used to group all the service interfaces into one Visual Studio project. All the Service Implementations are grouped into another project.
The consumer of the services needs to reference two dll but it makes the solution more maintainable and scalable. We can have multiple implementations of the services.
For e.g. the service interface can define a contract for WebSearch in the interfaces project. And there can be multiple implementations of the WebSearch through different search service providers like Google search, Bing search, Yahoo search etc.

structuring of web services

Consider 3 modules/classes in an ASP.NET Webforms application.
I need a web service for each of them, where each web service contains only one function.
Should I group them into one web service class, or should I keep the one web service for each class?
If they are related and need to be exposed for consumtion by a single client you could create one webservice and call this an API. This means you and your client maintain/consume a single webservice.
If they are clearly unrelated, separate them.
Group them in one class (the base webservice class). If it's needed you can branch from here and instantiate more complicated classes, or even call external libraries (for example if you have a data layer to call)

The Purpose of a Service Layer and ASP.NET MVC 2

In an effort to understand MVC 2 and attempt to get my company to adopt it as a viable platform for future development, I have been doing a lot of reading lately. Having worked with ASP.NET pretty exclusively for the past few years, I had some catching up to do.
Currently, I understand the repository pattern, models, controllers, data annotations, etc. But there is one thing that is keeping me from completely understanding enough to start work on a reference application.
The first is the Service Layer Pattern. I have read many blog posts and questions here on Stack Overflow, but I still don't completely understand the purpose of this pattern. I watched the entire video series at MVCCentral on the Golf Tracker Application and also looked at the demo code he posted and it looks to me like the service layer is just another wrapper around the repository pattern that doesn't perform any work at all.
I also read this post: http://www.asp.net/Learn/mvc/tutorial-38-cs.aspx and it seemed to somewhat answer my question, however, if you are using data annotations to perform your validation, this seems unnecessary.
I have looked for demonstrations, posts, etc. but I can't seem to find anything that simply explains the pattern and gives me compelling evidence to use it.
Can someone please provide me with a 2nd grade (ok, maybe 5th grade) reason to use this pattern, what I would lose if I don't, and what I gain if I do?
In a MVC pattern you have responsibilities separated between the 3 players: Model, View and Controller.
The Model is responsible for doing the business stuff, the View presents the results of the business (providing also input to the business from the user) while the Controller acts like the glue between the Model and the View, separating the inner workings of each from the other.
The Model is usually backed up by a database so you have some DAOs accessing that. Your business does some...well... business and stores or retrieves data in/from the database.
But who coordinates the DAOs? The Controller? No! The Model should.
Enter the Service layer. The Service layer will provide high service to the controller and will manage other (lower level) players (DAOs, other services etc) behind the scenes. It contains the business logic of your app.
What happens if you don't use it?
You will have to put the business logic somewhere and the victim is usually the controller.
If the controller is web centric it will have to receive its input and provide response as HTTP requests, responses. But what if I want to call my app (and get access to the business it provides) from a Windows application which communicates with RPC or some other thing? What then?
Well, you will have to rewrite the controller and make the logic client agnostic. But with the Service layer you already have that. Yyou don't need to rewrite things.
The service layer provides communication with DTOs which are not tied to a specific controller implementation. If the controller (no matter what type of controller) provides the appropriate data (no mater the source) your service layer will do its thing providing a service to the caller and hiding the caller from all responsibilities of the business logic involved.
I have to say I agree with dpb with the above, the wrapper i.e. Service Layer is reusable, mockable, I am currently in the process of including this layer inside my app... here are some of the issues/ requirements I am pondering over (very quickly :p ) that could be off help to youeself...
1. Multiple portals (e.g. Bloggers portal, client portal, internal portal) which will be needed to be accessed by many different users. They all must be separate ASP.NET MVC Applications (an important requirement)
2. Within the apps themselves some calls to the database will be similar, the methods and the way the data is handled from the Repository layer. Without doubt some controllers from each module/ portal will make exactly or an overloaded version of the same call, hence a possible need for a service layer (code to interfaces) which I will then compile in a separate class project.
3.If I create a separate class project for my service layer I may need to do the same for the Data Layer or combine it with the Service Layer and keep the model away from the Web project itself. At least this way as my project grows I can throw out the data access layer (i.e. LinqToSql -> NHibernate), or a team member can without working on any code in any other project. The downside could be they could blow everything up lol...

What's the best way to implement an API in ASP.NET using MVC?

I've been a longtime ASP.NET developer in the web forms model, and am using a new project as an opportunity to get my feet wet with ASP.NET MVC.
The application will need an API so that a group of other apps can communicate with it. I've always built API's out just using a standard web service prior to this.
As a sidenote, I'm a little hesitant to plunge headfirst into the REST style of creating API's, for this particular instance at least. This application will likely need a concept of API versioning, and I think that the REST approach, where the API is essentially scattered across all the controllers of the site, is a little cumbersome in that regard. (But I'm not completely opposed to it if there is a good answer to the potential versioning potential requirement.)
So, what say ye, Stack Overflow denizens?
I'd agree with Kilhoffer. Try using a "Facade" wrapper class that inherits from an "IFacade". In your Facade class put your code to consume your web service. In this way your controllers will simply make calls to the Facade. The plus side of this being that you can swap a "DummyFacade" that implements the same IFacade interface in that doesn't actually talk to the web service and just returns static content. Lets you actually do some unit testing without hitting the service. Basically the same idea as the Repository pattern.
I would still recommend a service layer that can serve client side consumers or server side consumers. Possibly even returning data in a variety of formats, depending on the consuming caller.

Resources