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

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

Related

Usage of data entities to exchange between client and microservices (asp.core)

Usually i create dto's to get data from microservice (WebApi) to client (MVC).
But sometimes it's cumbersome to duplicate structure of data entity to dto, especially if entity has multiple fields and many embedded relationships.
So i have to duplicate fields and relations.
Can i use data entity instead of dto?
I use a special assembly for dto's to be exchanged between client (MVC) and given microservice. Should my data entities live in this assembly?
This is a common complaint that derives from not understanding the concept of bounded contexts. Because you're deep in the code, you just see two things that look like the same thing, and you have had, like all developers, the idea beaten into your brain that you should not repeat yourself (DRY).
However, the key word above is that the two things look the same. They are in fact not the same, and that is the critical salient point. They are representations of domain objects from different contexts (data store and application layer, for example). If you use the same object, you are tightly coupling those contexts to the point where they're now inseparable. As such, the very concept of having multiple layers becomes moot.
A related concept here is anti-corruption layers. This is a layer you add to your application to facilitate communication between two different application contexts or domains. An API is a form of anti-corruption layer. Again, because you're building all the apps, it seems like they're all the same thing. However, imagine your MVC app as a third-party application being built by someone else to consume your API. Should they use your entities directly? No. They probably would have their own entity classes and their own data store. The DTO your API uses provides a way for these two different applications to communicate via a common language. If you use your entity classes directly, then any change to your data, necessitates a change to your API, which in turn necessitates a change to any consumers of your API. Imagine if Google changed a database column, and because of that, every single developer using their API(s) had to immediately make changes to their own applications or they would break.
In short, just because two classes look the same, doesn't mean they are the same. Your entity and your DTO are each representations of a concept in different contexts, and therefore you need and should have both.

REST WCF - best approach to expose entities or convert custom classes to Entity classes vice versa

I have taken a step back on two of the approaches in my project (WCF REST Service).
Started with WCFDataServices since it support full OData service stack, but due to more validation requirements on CRUD operations, switched to 'WCF Service' with EF.
And now thinking to step back to use Self-tracking entities to exposing entities to client, as many articles says STE is no more supported by Microsoft and preferred to use OData.(but again WCFDataService not suitable for me).
Please suggest what is the best design here to expose my entities over client.
Alternatively, I may have to write custom classes (Data Contracts) of Entity Model. But, this increases code (for conversion of objects between Custom and Entity) and decreases maintainability.
Please suggest is there any best approach to expose my entities. Your suggestions are valuable and most appreciated.
Fowlers first law of distributed object design states, "don't distribute your objects". This just means give them a copy and not the actual entity itself. If you were to create mirror copies of your entities in your data contract namespace, you retain much more flexibility, should your database schema need changing. If your data contract is initially identical to your entity, a tool such as AutoMapper will eliminate all the conversion code you need to write. Once configured, to convert your entity to your data contract becomes a 1 liner:
Mapper.Map<CustomerDto>(customer);
This takes your customer entity and gives you back a new customer dto. It's all convention based and works by matching up property names. Even if the data contract isn't entirely identical to the entity, you only have to prompt AutoMapper for those properties it can't figure out for itself.

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.

Exposing Entities through WCF

I have a WCF that uses a ADO.NET Entity Data Model to access SQL Server.
To insert a new row in a table with seven columns I'm using a WCF method.
I think send seven parameters it's too much, so I can use a struct or table's entity object.
What do you think? Do you recommend me to expose an entity object through WCF? Or I need to use a struct to avoid do that.
It depends on size / complexity of your application. Exposing entity is possible but it can cause some serialization problems when transporting whole object graph (entity with its relation). These problems are usually solved by marking entities with DataContract and DataMember attributes (used by default if you use EFv1 or default entity generation in EFv4 = no T4 templates).
The second approach you described is recommended if you want to follow clean architecture and good separation of concerns but it will make your application more complex (another layer of objects, conversions, etc.). Structures or classes created for data transportation are generally called DTOs (Data Transfer Objects).
Data Transfer Objects allow you transferring only necessary subset of data required for entity. If you for example have some infrastructural properties in the entity (like CreatedAt, CreatedBy) you will not want client to set these properties because it is responsibility of the service to set them. Because of that there is no need to allow client passing them. By not exposing these properties in the DTO you will make this clear.
My experience of using entities as Data Contracts is that you continually run into all kinds of hassle. Maintaining DTOs is not ideal, but gives you very fine grained control including the ability to change your DB schema without changing your contracts, and also control over the fields exposed by your service.
Automapper can really help you: http://automapper.codeplex.com/

WCF Object Design - OOP vs SOA

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.