Should the services in my service layer live in separate projects/DLLs/assemblies? - asp.net

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.

Related

Can a Service Layer contain multiple services?

I'm rearchitecting a large web forms ASP.Net application, inserting a service layer to take away unwanted responsibility from the presentation layer.
I've seen a lot of examples where all the service methods are contained in one class.
Is this common / best practice? Or is it perfectly feasible to have a number of service classes within the service layer? I'm leaning towards having more than one service and those services being able to talk to each other.
Any guidance, pros/cons?
Richard
P.s. Note that I'm not talking about a web service layer, WCF or otherwsie, although that might become more relevant at a later date.
The SOLID principles, specifically the Single Responsibility Principle would suggest that having all of your functionality in one object is a bad idea, and i tend to agree. As your application grows the single class will become difficult to maintain.
Your comments to Yuriys answer would suggest you want to use an IOC container. Lets consider that in more detail for a moment...
The more functionality this single class contains, the more dependencies it will require. You could well end up having a constructor on the service that has a long list of parameters, simply because the class covers a lot of ground and depends on other functionality at a lower level, such as logging, database communication, authentication etc. Lets say a consumer of that service wants to call one, and only one specific method on that class before destroying the instance. Your IOC container will need to inject every dependency that the service could 'possibly' need at runtime, even though the consumer will only use maybe 1 or 2 of those dependencies.
Also from an operational perspective - if you have more than one developer on the team working on the service layer at the same time, there is more possibility of merge conflicts if you are both editing one file. But, as suggested you could use partials to counter that issue.
Usually a dose of practicality alongside a well known pattern or principle is the best way forward.
I would suggest researching Service Orientated Architecture if you havent already, as it may help you answer some key decisions in the approach to your solution.
Of course, it can.
Moreover, I believe that would be better to extract from this God service layer class few interfaces by functionality (i.e. ISecurityService, INotificationService etc.) and implement each interface in separate project. Also, you can utilize some IOC container to resolve class that implement service's interface. This way you can change each service's implementation independently without changing client functionality.
At least, for the first time you can mark your service super class as partial, then split it up by functionality into few .cs(.vb) files with meaningful names and group them together in Visual Studio. This will simplify navigating across service methods.
My take on structuring an application would be to start with splitting the application into two projects AppX.Web (UI logic) and AppX.Business (business logic), but still keep them in the same VS solution. The clarify in structure between business logic and UI logic helps you understand what services are shared among multiple web pages and which are local to a singel web page. You should avoid reusing code directly between the web pages, if you find that this is necessary then you should probaly move that piece of shared code to the business logic layer.
When implementing the business logic project you should try to create separate classes for different type of business logic. These classes can of course talk to eachother, but do avoid having the web pages talk to eachother.
Once you have separated UI logic from business logic you can continue to break down the AppX.Business code into smaller pieces if necessary. Common examples include:
AppX.Data: A Data Access Layer (DAL) which isolate all data manipulation from the actual business logic
AppX.Dto: Data Transfer Objects (DTO) which can be useful in many scenarios, e.g. when sending data to the client browser for processing by jQuery
AppX.Common: Shared logic which is generic to many other applications, this can be helper classes you have previously created or things which should be reviewed after the project for inclusion in company wide support classes.
Finally, let's talk about going all-in and expose your business logic as a WCF service. In that case you actually need not change anything in the existing structure. You can either add the WCF service to your existing AppX.Web project or expose them separately in AppX.Service. If you have properly separated business logic from UI logic the WCF layer can be just a thin wrapper around the business logic.
When implementing the WCF service it is quite possible to do all of that in a single class. No real business logic is available in the WCF service as it just make direct calls to the business logic.
If you build a new application you should consider you overall design up front, but now that you are rearchitecting I think you should work step-by-step:
Start by creating the AppX.Web and AppX.Business Projects
Identify services and create classes in AppX.Business for those services
Move code from the AppX.Web project into the new classes in AppX.Business, and make sure you call them from the web project.
Continue with additional break-down if you feel you need to do so!

Creating/Exposing WCF services from an existing ASP.NET application

We need to expose some services (i.e. AddressValidatorService, CustomerFinderService) that currently reside in an ASP.NET application to other applications within our organization. Exposing these services via WCF seems like a natural fit, but I don't see any best-practices for how to pull these common services into a WCF wrapper in such a way that my existing ASP.NET application can continue to use them with minimal code changes and/or awareness that the service they are consuming is no longer in-process.
I'm especially looking for recommendations on how to structure the existing ASP.NET solution and whether to host our new WCF in the same solution or in some new shared WCF solution referenced by both our ASP.NET application and external callers.
Also, is it bad practice to simply promote the DTOs currently only consumed in-process via ASP.NET to full fledged data contracts or is it preferable to create duplicate DTOs that are explicitly decorated with [DataContract]? The latter seems like a maintenance nightmare.
To answer your second question:
Also, is it bad practice to simply promote the DTOs currently only consumed in-process via ASP.NET to full fledged data contracts or is it preferable to create duplicate DTOs that are explicitly decorated with [DataContract]? The latter seems like a maintenance nightmare.
It is considered a bad practice to expose your business model as WCF contracts. So if your DTOs are replicas of your domain model then it would be a strict no-no, because
1. any change in the model would directly effect the contracts and hence all the clients using it
2. you would be exposing your business "know-how" to the outside world.
The latter can tend to get difficult for any evolving system, but then you have various open source tools (like AutoMapper) that ease your mapping nighmares.
You can convert an existing project to WCF, then continue to use it in-process by using a project reference. It can then be consumed by an eternal source using the WCF client. A WCF client converts the class name from ClassName to ClassNameClient when consumed over WCF, but the class will function pretty much the same.
For example:
MyClass obj = new MyClass();
obj.DoSomething(withData);
Would become:
MyClassClient obj = new MyClassClient();
obj.DoSomething(withData);
You would publish the WCF project to some endpoint, like address.example.com, then use a service reference to the endpoint to reference the code, like a project reference, in your other projects.
Note that while the externally referencing projects would not be impacted by the change or know that the data is going over the network, if you have chatty calls to the project in question, it will definitely take a performance hit. You may want to consolidate related methods into single methods to save on round-tripping.
If these are exposed as static page services, there's no magic wrapper -- you're going to need to move code to a standalone service implementation class and put a .svc file in front of it. (Or use WCF4 fileless activation, or a service factory, but that's getting a bit away from the core question here.)
If these are exposed as ASMX, you can actually put an ASMX facade in front of a WCF service class and get basic HTTP/XML/ASMX responses as you would from your legacy ASMX webservices. You an expose that same WCF service class through standard WCF configuration for non-legacy consumers.
Finally, you can expose any WCF service as basicHTTP with serviceMetadata + httpGetEnabled, and you'll get a service endpoint usable by legacy consumers of an ASMX service.
http://msdn.microsoft.com/en-us/library/ms751433.aspx

Service Oriented real world sample application in ASP.NET

I've read lots of articles about Service Oriented architecture.
Is there any real world sample application which is imeplemented in ASP.NET?
Thanks
The short answers is: not that I know of.
The other thing to keep in mind (which you're probably already aware of) is that the level of abstraction is very important.
One one level, the "Service" in SOA is Business Service - not a technicial service like a web service; in fact at this level the idea of implementation is completely irrelevant. This is more at the Enterprise Architecture and Buisness Architecture level.
Lower-down, there's what you might call Service Orientated Design, where software systems are built in a way that is service based - it offers something that is easily consumed by other systems (or consumes a service in much the same way). Even at this point we're not talking about implementation specific things like technologu - it's just more of a mindset - how the system is arranged (the architecture).
The next level down is where software systems offer services as physical end-points that are defined by an address, binding and contract (The ABC of SOA).
At this level you will be able to find implementations; NServiceBus comes to mind (not that I have used it) - but you don't need a service bus to do "Service" orientated architecture.
Finally, I'm not sure exactly how you view ASP.NET in the context of your question. If you're .Net based then WCF is the place to start looking; one of the binding types is a web-service, which being web-based kind of comes under the umbrella of ASP.NET. Alternatively if you're building a website or web-application then the services that the application offers or consumes would be located in a data access or services layer - loosely-coupled to the Business Logic (BL) layer - so they aren't actually directly related to the fact you're doing a web-application at all, as this architecture woudl work for different kinds of application (not just web).

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...

Using a webservice as an interface for a data access layer in .NET

I am currently doing a CRUD project for school and basically they want us to have this kind of structure (3 projects):
Class Library
Contains all the data access logic (retrieving the data from the database with either LINQ of standard ADO.NET).
Web Service
Having a reference to the class library and offering [WebMethod]s that access the methods from the class library
ASP.NET Website
Having a service reference to the web service and using the WebMethods to retrieve the data
Which basically means that we cannot access the class library directly from the website:
Website
\
\
Web Service
\
\
Class Library
Now of course there are multiple solutions to choose from as to provide abstraction in the web service to separate for example methods that retrieve the articles and methods to retrieve the categories (which are two different entiries and have two seperate classes in the class libary):
I can either do one web service which will have all the methods (GetAllArticles, GetAllCategories, GetArticleByID, etc.) and the website only makes a reference to this one web service. But of course this will result in having all the methods in a single class (that is, a single web service)
Or I can create multiple web services (Articles.asmx, Categories.asmx etc...) and reference all of them from the website and then call the one I need depending on what data I need to retrieve.
But I mean for me, the above solutions are not really ideal because if I have the first solution, I will have a ton of methods all in one class (no abstraction whatsoever) and in the second solution, I will have to reference about 10 different web services from the website (one for articles, one for categories, etc.)
At school they told us to use the web service (or web services) to access the class library, and then retrieve the data from the class library using the Webmethods, but both solutions I mentioned earlier on seem a bit dodgy.
Is there a better way of how I might go about in implementing this structure?
In your example you suggested one service for Articles and one service for Categories. That may of course be just an example, but in that case it would not make sense to separate them, because it would be quite likely and common to have queries and/or routines which make use of both Category data and Article data.
With that in mind, it usually makes the most sense to group routines by the degree to which they are related to one another. If you can separate all your possible routines into, say, three clean groups with little to no overlap, then it makes sense to have three services. If you cannot cleanly separate any of your routines, you should limit yourself to one web service.
But regarding your statement "No abstraction" being a downside of one web service - that isn't necessarily true. You can always create layers of abstraction behind the web service, so that the service class itself is simply a facade with many thin method calls that reach into bulkier logic elsewhere.
In the end, the only approach which truly matters because it's the only approach which works is this: take the simplest approach possible, only build what you need to build in as few layers as you can; only add complexity when you reach a problem which cannot be solved in a better way than by adding that complexity. It is always easier to add complexity than to take it away.
I would put all the webmethods into the same class. The webmethods should only be wrappers around you business classes plus whatever input validation and authorisation you need.
Since web services are generally used by mahcines and not humans there is no pressing need for a hierarchy. It can become a burden to manage the URLs and web server if you create a webmethod class per business class.
If you are planning on using the HTML page that browsers automatically generate to call your web services as your main user interface you need to be a little bit careful. For example you won't be able to rely on SOAP headers if you need to authenticate requests.
Why not use ADO.Net Data Service?

Resources