WCF Object Design - OOP vs SOA - wcf

What is the proper way to handle polymorphic business objects in a WCF/SOAP world?
It seems to me that SOA and OOP are at odds with each other - to expose a clean WSDL you need concrete objects, typically not even utilizing inheritance. On the other hand, presumably in the underlying system, you'll want to follow proper OO design.
What do people typically do here? Build a set of WCF contract objects, forgoing OOP principles, then convert to and from another set of objects in the actual logic layers?

What do people typically do here? Build a set of WCF contract objects, forgoing OOP principles, then convert to and from another set of objects in the actual logic layers?
Yes.
The way WCF serializes things ends up putting a lot of limitations on what you can and can't do with the contract objects. What you can't do ends up being "most anything useful".
I've found it makes things much clearer if you think of the WCF-contract objects as just a data transfer mechanism. Basically like strongly/statically typed XML.
Instead of converting your business object to an XML string (and back again), you convert your business object to a WCF-contract object (and back again), but it's otherwise similar

After reading the Thomas Erl library, I came to the following conclusion:
Think of the WCF Contracts/SOAP Message as simply a message that the Services use to communicate (don't tightly tie that to Objects in your code).
You can then use OOP to design a code-base that gracefully handles those messages using common OOP techniques.

You use an abstraction (interface type) annotated with WCF attributes in order to define your Service contract.
This is both depending on abstraction, which is according to OOP, as well as defining a service endpoint, which is SOA.
In general, if you find that you are getting business objects with dependencies, you should consider pulling such dependencies up to the service business layer as opposed to inject dependencies into the business objects.
The service business layer will then act as a mediator acting on both the WCF service proxy as well as the business objects. As opposed to having the business objects acting on the WCF service proxy.

All great comments on this topic! I'll add my vote to the notion of an adapter for mediation between your service orientation and object orientation. I also like Thomas Erl's approach where in his service model he introduces the notion of "application services" and "business services." These are the way to go for your integration points with your specific application/business environment (i.e. your object oriented and component oriented framework/API). This way should result in much better composability and thus capability, for you enterprise framework gurus out there.

Related

WCF Message & Data Contract, DTO, domain model, and shared assemblies

I have a web client that calls my WCF business service layer, which in turn, calls external WCF services to get the actual data. Initially, I thought I would use DTOs and have separate business entities in the different layers... but I'm finding that the trivial examples advocating for DTOs, to be, well, trivial. I see too much duplicate code and not much benefit.
Consider my Domain:
Example Domain
I have a single UI screen (Asp.net MVC View) that shows a patient's list of medications, the adverse reactions (between medications), and any clinical conditions (like depression or hypertension) the patient may have. My domain model starts at the top level with:
MedicationRecord
List<MedicationProfile> MedicationProfiles
List<AdverseReactions> Reactions
List<ClinicalConditions> ClinicalConditions
MedicationProfile is itself a complex object
string Name
decimal Dosage
Practitioner prescriber
Practioner is itself a complex object
string FirstName
string LastName
PractionerType PractionerType
PractionerId Id
Address Address
etc.
Further, when making the WCF requests, we have a request/response object, e.g.
MedicationRecordResponse
MedicationRecord MedicationRecord
List<ClientMessage> Messages
QueryStatus Status
and again, these other objects are complex objects
(and further, complicates matter is that they exist in a different, common shared namespace)
At this point, my inclination is that the MedicationRecordResponse is my DTO. But in pure DataContracts and DTO and separation of design, am I suppose to do this?
MedicationRecordResponseDto
MedicationRecordDto
List<ClientMessageDto>
QueryStatusDto
and that would mean I then need to do
MedicationProfileDto
PractitionerDto
PractitionerTypeDto
AddressDto
etc.
Because I have show almost all the information on the screen, I am effectively creating 1 DTO for each domain object I have.
My question is -- what would you do? Would you go ahead and create all these DTOs? Or would you just share your domain model in a separate assembly?
Here's some reading from other questions that seemed relevant:
WCF contract know the domain
Alternatives for Translation Layer in SOA: WCF
SOA Question: Exposing Entities
Take a look on excellent articles
Why You Shouldn’t Expose Your Entities Through Your Services
DTO’s Should Transfer Data, Not Entities
above links don't work, looks like a domain issue (I hope it'll be fix), here is the source:
DTO’s Should Transfer Data, Not Entities
Why You Shouldn’t Expose Your Entities Through Your Services
I've always had an aversion to the duplicate class hierarchy resulting from DTOs. It seems to be a flagrant violation of the DRY principle. However, upon closer examination, the DTO and the corresponding entity or entities serve different roles. If you are indeed applying domain-driven design then your domain entities consist of not only data but behavior. By contrast, DTOs only carry data and serve as an adapter between your domain and WCF. All of this makes even more sense in the context of a hexagonal architecture also called ports and adapters as well as the onion architecture. Your domain is at the core and WCF is a port which exposes your domain externally. A DTO is part of how WCF functions and if you agree that it is a necessary evil your problem shifts from attempting to eliminate them to embracing them and instead focusing on how to facilitate the mapping between DTOs and domain objects. A popular solution is AutoMapper which reduces the amount of boiler plate mapping code you need to write. Aside from the drawbacks, DTOs also bring a lot of benefits. One is that they furnish a buffer between your domain entities and the outside world. This can be of great help in refactoring because you can keep your core domain very well encapsulated. Another benefit is that you can design your DTOs such that they fulfill requirements of the service consumer, requirements which may not always be in full alignment with the shape of your domain objects.
Personally, I don’t like using MessageContract as entities. Unfortunately, I have an existing WCF service that use MessageContract as entities – i.e. data is filled into the MessageContract directly in the data access layer. There is no translation layer involved.
I have an existing C# console application client using this service. Now, I have a new requirement. I need to add a new field in the entity. This is not needed by the client. The new field is only for the internal calculations in the service. I had to add a new property named “LDAPUserID” in the MessageContract which also act as a entity.
This may or may not break the client depending on whether the client support Lax Versioning. Refer Service Versioning.
It is easy to mistakenly believe that adding a new member will not break existing clients. If you are unsure that all clients can handle lax versioning, the recommendation is to use the strict versioning guidelines and treat data contracts as immutable.
With this experience, I believe it is not good to use MessageContract as entities.
Also, refer MSDN - Service Layer Guidelines
Design transformation objects that translate between business entities and data contracts.
References:
How do I serialize all properties of an NHibernate-mapped object?
Expose object from class library using WCF
Serialize subset of properties only

Dynamic data contracts in WCF

There are some pain points around transmitting entities between a client and a WCF service.
Defeating lazy loading by serializing all properties
Serialized data can be unecessarily bloated
Some coupling between UI and business layer
One way to address these issues is to transmit DTOs instead of entities but I am aware that this technique has its own set of caveats (the biggest one I am aware of is the typing required to maintain these function-specific DTOs).
I think it would be great if the service implementation could generate these DTOs dynamically and this appears to be possible. Unfortunately, it looks like the contract would be loosely defined on the client side (i.e. "object") and that smells like a possible risk.
Is it advisable to use dynamic DTOs in this fashion or is there another way to use DTOs without creating/maintaining classes for each one?
I think the holy grail would be where the implementation dynamically generates DTOs but the client sees well-defined contracts. I'm guessing this isn't possible with WCF.
I guess the issue is what are you going to generate them from? You have to have some description somewhere of what the data you want to transmit looks like. If all you have is the domain objects then you end up in a similar position of transmitting the data that you would of via the domain object.
One of the key things the DTO enables is decoupling so you can evolve your domain objects without breaking the consumers of your service accidently. If you dynamically generate the DTOs then you will cascade the changes - unless you view the dynamic creation as a one-off exercise to get you started with a DTO
DTO is data contract as any other and must be defined. When you choose to go with DTOs you are adding a layer of complexity which you have to maintain. There are tools which can help you with mapping between domain objects and DTOs (like AutoMapper) but your responsibility is to define what DTO should transfer - that is something which can hardly be done automatically. Even with automated tool you will still have to maintain some definition of DTOs which will be used to generate code.

Making OR/M loosely coupled and abstracted away from other layers

In an n-tier architecture, the best place to put an object-relational mapping (OR/M) code is in the data access layer. For example, database queries and updates can be delegated to a tool like NHibernate.
Yet, I'd like to keep all references to NHibernate within the data access layer and abstract dependencies away from the layers below or above it. That way, I can swap or plug in another OR/M tool (e.g. Entity Framework) or some approach (e.g. plain vanilla stored procedure calls, mock objects) without causing compile-time errors or a major overhaul of the entire application. Testability is an added bonus.
Could someone please suggest a wrapper (i.e. an interface or base class) or approach that would keep OR/M loosely coupled and contained in 1 layer? Or point me to resources that would help?
Thanks.
It sounds like you are looking for the repository pattern. If you need more decoupling, you can inject the data dependencies with an Inversion of Control container.
Service Facade Pattern is one name. Simple contracts between business logic and data layer.
Service classes or beans (call it what you want) define and implement the contract, and orchestrate the lower data layer, often handling the transactional logic across data objects.
In Spring, you define an Interface, and then implement it. One implementation might be an OR/M, another might be raw JDBC or ADO.NET. In some frameworks, Aspect Oriented Programming allows you to inject declarative transactional logic without writing any code. It saves a lot of headache.
One caveat: When dealing with some OR/Ms like Hibernate, there is the use of proxy classes. This does pollute things, because there are a few instances where the proxy classes cause problems. In my opinion, that is an implemtation detail that should not escape the service layer. But with Hibernate, it does. Not sure about the .NET implementation.

How complex an object can be passed to silverlight from server, using WCF?

Please note that my experience in Silverlight/.Net and WCF is about two weeks of googling and deciphering tutorials. I need to attempt and provide feedback to a client on if Silverlight will be a possible solution to their application needing a RIA front end.
The client has a rather large .Net based application with a UI layer built which greatly relies on the creation and manipulation of specific (personal) classes and objects from the backend (which would be the server side).
A summery of what I understand to be the general procedure: one can pass simple objects containing simple data types, or more complex .Net type objects. Basically anything which can be understood by both client and server side, after serializing.
But what is the limitation to the complexity of an object I can pass? Or phrased otherwise, would silverlight and WCF be able to support the passing of a personalized object which may contain references to other classes/objects and variables etc?
Additional Info (in case it can help):
I am not allowed direct access to their backend code but with the information I have been given I can safely say their classes heavily use inheritance and overloading of functions/methods in the classes.
As far as I know there is nothing specific to Silverlight. There are some things to keep in mind though.
WCF serialization doesn´t like circular references.
All types need to specified in the contract. So watch out with inheritance etc.
In general using DTO's (Data Transfer Objects) and not exposing your business objects is the way to go.
The metaphor is one of message passing as opposed to passing objects. DTO's as Maurice said.
You can get pretty complex, but each object needs to have its contract defined.

How to use the single responsibility principle in large wcf services?

We're using about 7 services at the moment. There quite large.
Does anyone have any experience with the single responsibility principle and WCF services? Does this mean that you'll end up with lot's of small contracts? If so, how do you manage these in your application?
I think you are confusing single responsibility with interface segregation.
From the client/service interface perspective, you should keep your contracts lean and mean. See below for an example of that.
On the SRP side of things, that should be entirely internal to the service implementation and the client should not be aware of this. If you service code is too large, split it up into classes. Then have your service code, at least initially, act as a facade and forward all the calls to the relevant objects. Later on, you have the option of spliting your service into multiple services. But be aware, that SOA and object oriented design, although overlap, are separate and have different requirements.
Interface segregation example: We have a service here at work that we use to do various functions on some business objects. The original service had one interface. As it grew, we realized we had three family of methods: data object persistence, business updates, business analysis. We split up into three contracts. Our client/service implements all 3, so the only thing we had to do was split the contract into three and setup two additional endpoints in our WCF configuration. Very simple.
Hope this helps.
I would suggest you listen to this podcast on the hanselminutes :
SOLID Principles with Uncle Bob - Robert C. Martin
It would help understand things better. . .
You could apply facade pattern for the web service that interface with the client, and in your implementation code you can apply single responsibility to make it maintainable.