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

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

Related

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.

what is the best Session management opt ion for Asp.net mvc - wcf - BLL - Nhibernate repository

I have an application architecture which has following layers (or c# projects).
web front end (asp.net mvc2)
service layer (normal c# class library)
Model layer (normal c# class library with entities, service and repository Interfaces)
Data layer (implements repository interface defined in BLL and uses NHibernate)
ISession is opened per http request and its working fine.
Now, I would like to add wcf layer on top of my current service layer. wcf project plainly calls original service layer classes. But as soon as I do this, the session/session factory at asp.net becomes unusable/unavailable. Looks like, wcf is running in totally different context than asp.net. Hence I would like to move the logic of initinializing session factory and session management to wcf. How should I do it? and even before is it a good practice? one of the reason I would like to add wcf is because I want to expose the operations to other applications (which may not be http based).
Any help, blog post or book reference would be greatly appreciated.
Use Per-call instancing of NHibernate session. Check this article. It explains how to create attribute which will attach Session to current instance context.
you probably want to have WCF running in the same context as asp.net... try this article:
http://msdn.microsoft.com/en-us/library/aa702682.aspx

WCF vs ASPX webmethods vs ASMX webmethods

The intent is to create a set of web services that people can reuse. These services mostly interact with a backend DB creating, retreiving and processing data.
We want to expose services so that people can use to create data mashups and other applications.
End users are webpages that can be within our domain or outside our domain. For pages outside the domain we plan to release widgets that would be configured to retreive and display the data.
One requirement - application should be extremely scalable in terms of the number of users it can handle.
Our code base is .net and we are looking at ASPX webmethods (or ASHX), ASMX webmethods and WCF (starting to read up on WCF).
In terms of security/access I found that maintaining sessionid, memberships is doable in all three. WCF seems a bit complicated to setup. I could not immediately see the value of asmx when we can get all done just using a webmethod in aspx (with a little tweaking).
Also, assuming that with the ASP.NET MVC2 I might be able to get clean urls as well for these webmethods.
Questions
Which one will be the most effective in terms of performance and scalability?
Any reason why I should choose WCF or ASMX?
Thank you for taking the time to read through this post and apologies for the naive questions since I am new to .net.
EDIT I kind of understand that WCF is the way to go. Just to understand the evolution of the technologies it would be good if someone can throw light on why a aspx webmethod is different from an asmx when similar things (apart from discovery) can be accomplished by both. The aspx webmethods can be made to return data in other formats (plaintext, json). Also, it seems that we can build restful services using ashx. Apologies again for the naive questions.
You should use WCF for developing webservices in .Net. WCF is highly configurable with many options for security, transport protocols, serialization, extensions etc. Raw performance is also significantly higher. Also WCF is being actively developed and many new features being added in version 3.5 and 4. There are also variations like WCF data services and WCF RIA services. WCF 4.0 also has better REST and JSON support which you can directly use in ASP.Net / JQuery.
ASMX is considered deprecated technology and replaced by WCF. So if you are going to start new development which requires exposing reusable services, WCF is the way to go.
I am not necessarily disagreeing with previous answer. But, from a different perspective, WFC is tricky to configure. It requires bindings, endpoints, packet sizes, a lot of confussing parameters, etc in your configuration files, and there are many serialization/deserialization issues reported. Also WCF is a relatively new technology (therefore still exposed to bugs and patches needed).
The client-generated [Reference.cs] files might have unwanted interfaces, and each public property client class exposed in the WSDL gets generated with the same observer pattern that LINQ to SQL or Entity Framework uses ( OnChanged, OnChanging, etc) so this adds a lot of fat to the client code, as opposed to the traditional SOAP Web client way.
My recommendation, if you aren't using Remoting over TCP or if you don't need the 2-way notification mechanism for remote changes - all these are very cool features of WCF - you don't need to use it.

Avoiding having to map WCF's generated complex types

I have an ASP.NET MVC web app whose controllers use WCF to call into the domain model on a different server. The domain code needs to talk to a database and access to the database server isn't always possible from web servers (depends on the customer site) hence the use of WCF to get to a place where my code is allowed to connect to the database server.
This is configurable so if the controllers are able to access the database server directly then I use local instances of the domain objects rather than use WCF.
Lets say I have a page asking for person details like age, name etc. This is a complex type that is a parameter on my WCF operation like this :
[OperationContract]
string SayHello( Person oPerson);
When I generate the client code (eg; by adding a service reference in my client) I get a separate Person class that fulfills the wcf contract. The client, an MVC web app, can use this client Person class as the view model and all is well. I pass that straight into the WCF client methods and it all works brilliantly.
If my mvc client app is configured to NOT use WCF I have a problem. If I am calling my domain objects directly from the controller (assume I have a domain access factory/provider setup) then I need the original Person class and not the wcf generated Person class. This results in my problem which is that I will have to perform mapping from one object to another if I don't use WCF
The main problem with this is that there are many domain objects that will need to be mapped and errors may be introduced such as new properties forgotten about in future changes
I'm learning and experimenting with WCF and MVC can you help me know what my options are in this scenario? I'm sure there will be an easy way out of this given the extensibility of WCF and MVC
Thanks
It appears that you are not actually trying to use a service-oriented architecture. In this case, you can place the domain objects into a single assembly, and share it between the WCF service and the clients. When creating the clients, use "Add Service Reference", and on the "Advanced" tab, choose "Share Types". Either choose to share all types, or choose the list of assemblies whose types you want to share.
Sound service-oriented-architecture dictates that you use message based communication regardless of whether your service is on another machine, in another process, in another appdomain, or in your appdomain. You can use different endpoints with different bindings to take advantage of the speed of the link (http, tcp, named pipes) based on the location of your service, but the code using that service would remain the same.
This may not be the easiest or least time-consuming answer, but one thing you can do is avoid using the "add service reference" option, and then copy your contract interfaces to your MVC application and initiate the connection to WCF manually without automatically creating a service proxy. This will allow you to use one set of classes for your model objects and you can control explicitly when to use WCF or not.
There's a good series of webcasts on WCF by Michele Leroux Bustamante, and I think in episode 2, she explains how to do exactly this. Check it out here: http://www.dasblonde.net/WCFWebcastSeries.aspx
Hope this helps!
One sound option is that you always use WCF, even if client and server are in the same process, as Aviad points out.
Another option is to define the service contracts on interfaces, and to put these, together with the data contracts into an assembly that is shared between client and server. In the client, don't use svcutil or a service reference; instead, use ClientFactory<T>.
This way, your client code will use the same interfaces and classes as the server.

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