Service contracts vs. domain objects - wcf

Say I have two interfaces to my application:
A web front-end
A back-end which provides data
Both of them talk to a web-service, and that web-service in turn, handles business logic and talks to a separate data layer, which persists the objects.
So, if each client of the web-service uses the DataContracts of that web-service, what do I need domain objects for?
Where does domain-driven design fit in here, and what advantages does it bring to my architecture?
Or is it that case that what I have already is fine, and I don't need domain objects at all?
Am I misunderstanding the meaning and purpose of domain-driven-design?

The data contracts are nothing more than messages that your client and server exchange between each other.
Your WCF service is that layer which accepts the messages and processes them so that they can be handled by your business logic.
Your domain objects would be your business logic, which accepts the processed messages, performs the necessary actions, and then applies any events that need to be applied.
If you follow a more Command-Query Separation principle (CQS), then your commands (inserts/updates/deletes) would be fired off to the WCF service and not return anything. Your client would request reads from your WCF service separate from your commands (meaning a InsertOrder command doesn't return an Order - you have to issue a separate request for that).
In all of that, your data contracts are the messages to and from your WCF service. Your domain is behind that service handling all of the business logic that needs to happen in order to make your reads as accurate as possible.
I'm answering this from more of a CQRS (command-query responsibility segregation) perspective, but I hope this explains where I'm coming from.
To answer your other question:
- do you need domain objects --> I'd say yes, you should

What do I need domain objects for?
You may not need domain objects in your application. Typically, DDD would fit into a service layer in the following way: The service layer exposes its operation contracts and data contracts. Data contract classes often correspond to objects in your domain, but they are not domain objects because they don't have any behavior, they are only a representation of the data with which a particular service is concerned. Here is a simple example interaction between data contract objects and domain objects in a service:
public MyEntityDto GetMyEntity(string id) {
var entity = this.myEntityRepository.Get(id);
if (entity == null)
return null;
return new MyEntityDto(entity);
};
In this case, MyEntityDto is a DTO object for MyEntity, it serves to expose the specific properties of MyEntity which the service wishes to provide to its clients.
The value of DDD comes into play when your domain is more complex and has associated behavior:
class MyEntity {
public void ChangeState(MyEntityState state) {
if (!IsValidState(state))
throw new Exception("Not a valid state.");
// further domain logic here...
}
}
[DataContract]
class ChangeStateCommand {
[DataMember]
public string MyEntityId { get; set; }
[DataMember]
public string State { get; set; }
}
public void Process(ChangeStateCommand command) {
var entity = this.myEntityRepository.Get(command.MyEntityId);
if (entity == null)
throw new SomeException().
entity.ChangeState(command.State);
this.myEntityRepository.Commit();
}
In this case, the data carried my ChangeStateCommand is used to operate upon your domain entity.

Related

How do I gracefully avoid dependencies on infrastructure services from domain entities using DDD?

Background
Suppose I am tasked with building a system in the domain of notification sending using Domain Driven Design (DDD). One of the key requirements of this system is that it needs to support various "types" of notifications, such as SMS, email, etc.
After several iterations on developing the domain model, I continue to land on having a Notification base class as an entity, with subclasses SMSNotification, EmailNotification, etc. as child classes (each being an entity as well).
Notification
public abstract class Notification extends Entity<UUID> {
//...fields...
public abstract void send();
}
SMSNotification
public class SMSNotification extends Notification {
public void send(){
//logic for sending the SMS notification using an infrastructure service.
}
}
EmailNotification
public class EmailNotification extends Notification {
public void send(){
//logic for sending the email notification using an infrastructure service.
}
}
Problem(s)
With this current design approach, each subclass of Notification is interacting with an infrastructure service, where the infrastructure is tasked with interfacing with some external system.
Eric Evans dedicates a little page space about this on page 107 in his book Domain-Driven Design when introducing the concept of domain services:
..., in most development systems, it is awkward to make a direct interface between a domain object and external resources. We can dress up such external services with a facade that takes inputs in terms of the model, ... but whatever intermediaries we may have, and even though they don't belong to us, those services are carrying out the domain responsibility...
If instead, I procure a SendNotificationService in my domain model using Evans' advice instead of having a send method on each subclass of Notification, I am not sure how I can avoid the need for knowing what type of notification was provided, so that the appropriate infrastructure action can be taken:
SendNotificationService (Domain Service)
public class SendNotificationService {
public void send(Notification notification){
//if notification is an SMS notification...
// utilize infrastructure services for SMS sending.
//if notification is an email notification...
// utilize infrastructure services for email sending.
//
//(╯°□°)╯︵ ┻━┻)
}
}
What am I missing here?
Object oriented design principles are pushing me in favor of having the model first suggested, with the Notification, SMSNotification, and EmailNotification classes. Implementing the send method on each subclass of Notification makes sense, as all notifications need to be sent (justifies its placement in Notification) and each "type" or subclass of Notification will have specialized behavior in how the notification is sent (justifies making send abstract in Notification). This approach also honors Open/Closed Principle (OCP), since the Notification class will be closed to modification, and as new notification types are supported, a new subclass of Notification can be created to extend functionality. Regardless, there seems to be consensus on not having entities interface with external services, as well as not having subclasses of entities at all in DDD.
If the behavior of sending notifications is removed from Notification, then where it is placed must be aware of the "type" of notification, and act accordingly, which I can only conceptualize as chain of if...else... statements, which directly contradicts OCP.
TLDR: If you need some infrastructure logic to be executed against your domain and you need some input to it from domain - don't build it in, just declare intentions with appropriate data/markers. You'll then process this declared intentions later, in infrastructure layer.
Do notifications of various kind differ in any way other that delivery mechanism? If not - there could be enough to use a Notification value object (or Entity, if your domain model requires so) with additional field (Enum, if the list is known, or some kind of marker) to store a delivery method name. Maybe, there could be numerous such methods per single notification instance.
Then you have a business logic - a domain service - to fire a notification. A domain service should only depend on domain vocabulary. E.g NotificationDeliveryMethodProvider.
In your adapters layer you can implement various delivery method providers to interact with infrastructure. And a factory to get providers according to a value in DeliveryMethod enum (or marker).
Basically, it's not an aggregate's responsibility to "send" itself of manipulate in any way. Its responsibility should be to maintain its state, execute state transitions in a consistent way and coordinate states of its enclosed entities/values. And fire events about its state changes.
In one of my projects I used the following subpackages under my domain package:
provides - interfaces of domain services provided to clients
cousumes - interfaces of upstream dependencies
businesslogic - implementation of domain services
values - value objects with code to enforce their invariants
...
Besides domain package there were also:
adapters package dealing with infrastructure
App object, where all interfaces were bound to implementations.
[There could also be] config package, but in my case it was very light.
These domain, adapters, App and config could be deployed as different jar-files with clear dependency structure, if you need to enforce it for somebody other.
I agree with you that the main responsibility of a Notification should be, that it can send itself. That is the whole reason it exists, so it's a good abstraction.
public interface Notification {
void send();
}
The implementations of this interface are the infrastructure services you are looking for. They will not (should not) be referenced directly by other "business" or "core" classes.
Note about making in an Entity: My own takeaway from reading the blue book is, that DDD is not about using Entity, Services, Aggregate Roots, and things like that. The main points are Ubiquitous Language, Contexts, how to work the Domain itself. Eric Evans himself says that this thinking can be applied to different paradigms. It does not have to always involve the same technical things.
Note about the "conventional" design from the other comment (#VoiceOfUnreason): In object-orientation at least, "holding state" is not a real responsibility. Responsibilities can only directly come from the Ubiquitous Language, in other words from the business. "Conventional" (i.e. procedural) design separates data and function, object-orientation does exactly the opposite. So be sure to decide which paradigm you are aiming for, then it may be easier to choose a solution.
After several iterations on developing the domain model, I continue to land on having a Notification base class as an entity, with subclasses SMSNotification, EmailNotification, etc. as child classes
That's probably an error.
public abstract class Notification extends Entity<UUID> {
public abstract void send();
}
That almost certainly is. You can make it work, if you twist enough, but you are going the wrong way around.
The responsibility of the entities in your domain model is the management of state. To also have the entity be responsible for the side effect of dispatching a message across your process boundary violates separation of concerns. So there should be a collaborator.
For Evans, as you will have noted, the collaboration takes the form of a domain service, that will itself collaborate with an infrastructure service to produce the desired result.
The most straight forward way to give the entity access to the domain service is to simply pass the domain service as an argument.
public class SMSNotification extends Notification {
public void send(SMSNotificationService sms) {
//logic for sending the SMS notification using an infrastructure service.
}
The SMSNotification supports a collaboration with an SMSNoticationService provider, and we make that explicit.
The interface you've offered here looks more like the Command Pattern. If you wanted to make that work, you would normally wire up the specific implementations in the constructor
public class SMSCommand extends NotificationCommand {
private final SMSNotificationService sms;
private final SMSNotification notification;
public final send() {
notification.send(sms);
}
}
There are some things you can do with generics (depending on your language choice) that make the parallels between these different services more apparent. For example
public abstract class Notification<SERVICE> extends Entity<UUID> {
public abstract void send(SERVICE service);
}
public class SMSNotification extends Notification<SMSNotificationService> {
public void send(SMSNotificationService service){
//logic for sending the SMS notification using an infrastructure service.
}
}
public class NotificationCommand<SERVICE> {
private final SERVICE service;
private final Notification<SERVICE> notification;
public final send() {
notification.send(service);
}
}
That's the main approach.
An alternative that sometimes fits is to use the poor man's pattern match. Instead of passing in the specific service needed by a particular type of entity, you pass them all in....
public abstract class Notification extends Entity<UUID> {
public abstract void send(SMSNotificationService sms, EmailNotificationService email, ....);
}
and then let each implementation choose precisely what it needs. I wouldn't expect this pattern to be a good choice here, but it's an occasionally useful club to have in the bag.
Another approach that you will sometimes see is to have the required services injected into the entity when it is constructed
SMSNotificationFactory {
private final SMSNotificationService sms;
SMSNotification create(...) {
return new SMSNotification(sms, ...);
}
}
Again, a good club to have in the bag, but not a good fit for this use case -- you can do it, but suddenly a lot of extra components need to know about the notification services to get them where they need to be.
What's best between notification.send(service) and service.send(notification)
Probably
notification.send(service)
using "Tell, don't ask" as the justification. You pass the collaborator to the domain entity, and it decides (a) whether or not to collaborate, (b) what state to pass to the domain service, and (c) what to do with any state that gets returned.
SMSNotification::send(SMSNotificationService service {
State currentState = this.getCurrentState();
{
Message m = computeMessageFrom(currentState);
service.sendMessage(m);
}
}
At the boundaries, applications are not object oriented; I suspect that as we move from the core of the domain toward the domain, we see entities give way to values give way to more primitive representations.
after reading a bit on pure domain models and the fact there shouldn't be any IO in there I'm not sure anymore
It is, in truth, a bit of a tangle. One of the motivations of domain services is to decouple the domain model from the IO -- all of the IO concerns are handled by the domain service implementation (or more likely, by an application/infrastructure service that the domain service collaborates with). As far as the entity is concerned, the method involved is just a function.
An alternative approach is to create more separation between the concerns; you make the orchestration between the two parts explicit
List<SMSRequest> messages = domainEntity.getMessages();
List<SMSResult> results = sms.send(messages)
domainEntity.onSMS(results)
In this approach, all of the IO happens within the sms service itself; the interactions with the model are constrained to in memory representations. You've effectively got a protocol that's managing the changes in the model and the side effects at the boundary.
I feel that Evans is suggesting that service.send(notification) be the interface.
Horses for courses, I think -- passing an entity to a domain service responsible for orchestration of multiple changes within the model makes sense. I wouldn't choose that pattern for communicating state to/from the boundary within the context of a change to an aggregate.

Web service coordination

We are creating a WCF infrastructure to allow other systems in the organization to consume our business logic. Some of this logic has to do with user authentication, so securing the services is of high concern. The transport layer is secured by certificates. I am more concerned with securing the business layer.
One of our clients calls these services in a certain sequence, in order to support a business process. What I would like to do is put in place some mechanism to verify that the sequence is indeed kept. The sequence can be disrupted by developer errors on the consuming side or by attackers trying to compromise the system. I do not want to put the logic of the process inside the services themselves, since this will couple them to this specific client`s process. I would like to put the logic for coordinating the different services in a separate layer, which will be client specific (or maybe something more generic to support any process?)
Can someone point me to specific patterns or resources which discuss this issue?
I have been searching Google for half a day, and I can`t seem to find any resource discussing this specific issue.
Most web services should be designed to be called independently, since there's no guarantee what order the caller will compose them.
That having been said, one way to encourage them to be called in order is to use a design akin to a Fluent Interface, in which Service A returns an object that is an input parameter to Service B.
[DataContract]
public class ServiceAResult
{
// ...
}
[DataContract]
public class ServiceBResult
{
// ...
}
[ServiceContract]
public interface IServiceA {
[OperationContract]
public ServiceAResult OperationA() {
// ...
}
}
[ServiceContract]
public interface IServiceB {
[OperationContract]
public ServiceBResult OperationB(ServiceAResult input) {
// ...
}
}
Here, the easiest way to create a ServiceAResult to pass to ServiceB.OperationB is to call ServiceA.OperationA.
I recommend you separate your concerns.
Have a web service whose operations are called in order to perform your business processes.
Have a second service which orchestrates your business processes and which calls the operations of the first service in the required order.
Do not make it the responsibility of the first service to ensure that the second service calls things in the correct order. The responsibility of the order of calls should belong to a different service.

Architecting of a business layer between WCF data layer and WPF front end

I am designing a data driven windows application, to be fed not by the underlying SQL Server but by a WCF service, so as to allow access locally and remotely.
Said WCF provides specific features for the retrieval of users, stock, customers etc, and actually performs the ADO operations, along the following lines:
[OperationContract]
UserAdapter GetUserByWindowsIdentity(string Domain, string Account);
Which returns one of:
[DataContract]
public class UserAdapter
{
[DataMember]
public int? ID;
[DataMember]
public string Domain;
[DataMember]
public string Account;
[DataMember]
public string Name;
}
Rather than have specific references to my WCF client in my WPF front end application, I should like to abstract some further functionality in another layer in between - for example, validating a users logon via their WindowsIdentity belongs neither in the data layer, nor the presentation layer, but an intermediary business logic layer.
I am uncertain how to go about this. I'd prefer in my presentation layer to be able to do something along the lines of:
User.Login();
and for the User object to abstract the same properties like Domain, Account, etc, as per my UserAdapter class, but I can't subclass this because I can't downcast the objects returned by my data layer.
Any suggestions where I can take this, including 'chuck it out' would be very much appreciated. Thank you all!
An additional layer in between makes absolutely sense if you have some business logic, the implementation details depend on your requirements of course.
If you think about it, the underlying data class should not know how to login, since that is already business logic: this is actually the real problem behind the approach you considered.
Hiding the business logic behind another set of services is also an option you should consider, getting all the benefits (and the cost of ownership) of WCF at business logic level.
Dino Esposito wrote a good book about architecting enterprise applications, maybe you can find some inspiration there for implementing your layered architecture.

Domain Model – Repositories – Communication across Sub-Systems

I am currently in the process of designing a system which will use multiple data sources to consume the required data. I am attempting to model the concepts shown below (would post an image but don't have enough points!) where a customer can have an association with a number of products. The Customer would be stored in the "Customer subsystem" and the Product and CustomerProduct would be stored in thee "Product subsystem"
public class Customer
{
public string FirstName { get; set; }
public Guid ID { get; set; }
}
public class CustomerProduct
{
public Guid ID { get; set; }
public Customer Customer { get; set; }
public Product Product { get; set; }
}
public class Product
{
public string Name { get; set; }
public double Price { get; set; }
public Guid ID { get; set; }
}
The “Customer” entity will be physically persisted in a system which must be accessed via a web-service. The “ConsumerProduct” and “Product” entities will be persisted in a SQL database, using NHibernate as the ORM.
As part of the design I was planning to use Repositories to abstract the data persistence technologies away from the domain model. Therefore I would have 3 repository interfaces, ICustomerRepository, ICustomerProductRepository and IProductRepository. I would then create a concrete NHibernate implementation for the CustomerProduct and Product repositories and a concrete web service access implementation for the Customer repository.
What I am struggling with is how the entities, which are persisted in different sub-systems will interact. Ideally I would like a rich domain model, where the CustomerProduct entity would have a physical “Customer” property which returns a Customer object. However I have no idea how this would work as the Customer entity would need to be accessed from a different data store.
The only way I can see to solve this issue is to not maintain a full reference to Customer in the CustomerProduct entity and instead just hold a reference, and then every time I need to get a reference to the Customer I would just go via the Customer Repository.
I would be grateful for any suggestions anyone could put forward on how to solve this issue.
hi I haven't been in your situation before, but I have designing domains that communicate with other subsystems.
I do not have the whole picture, but it seems like the customer entity is more isolated from the others, CustomerProduct and Product. So am I guessing correct that you will present the model in a common GUI but its only the datasource that are separated?
First you can solve this by different ways and you should also ask yourself about non-functional requirements such as maintenance, uptime and support. Will both systems always be up and running simultaneously or will it happened that you take on system down. The clue I'm fishing for is should you communicate sync or async (message queuing?) with subsystems. This can be achieved by using NServiceBus.
But to focus on your Domain, you should go for making the Domain look like it only has one model. This can be accomplished in different ways:
1) Have your ICustomerRepository (an interface contract that acts like is working against a collection of objects) be implemented by a infrastructure related repository that consume your web service in your subsystem. A hint is that you should use GUID as keys so keyconfilcts occur. This approach will not let you have any relationships/associations to customer from your other entities. They will but only through the repository (This a solution that Jimmy Nilsson uses in his book (http://jimmynilsson.com/blog/) to not tighten the model with to many bidirectional relationships).
2) Depends how your use cases will target/use the model, but you can create a application wide service layer that resides at one physical place but uses CustomerService and CustomerProcuctService and ProductService. To prevent that domain logic will leak into application layer some of the coordination between these entites can be encapsulated in a domain event handlers that coordinate some events between different services.
3) you can also create a CustomerAdapter class that have the other subsystems CustomerGUID as a key (it cannot generate keys since Customer webservice have control of that). But you can map it in Nhibernate and have relationsship between CustomerProduct and CustomerAdapter. But when you Map CustomerAdapter you will only load the GUID. Then make sure you will have a ICustomerAdapterService injected into a property using Spring.Net Windsor or some other DI tool. Then you to not map properties (like customername, adress etc) for customerAdapter in Nhibernate. But when you get/read Adress from CustomerAdapter it will get it from ICustomerAdapterService and set all other values as well.
This is not a recommended solution since it will break some DDD rules, like not having services in domain model. But if you see it from this perspective: it actually can be considered a Domain Service since it solves problem within your distributed domain. However it includes infrastructure related things like a WCF service implementation and therefore should the service implementation be in another infrastructure layer/assembly
Most simple is the solution 2 If you can handle the fact that Customer Entity will be accessed only by a Service in application layer.
However this application serviclayer can be a good anticorruption layer between the two subsystems. There is probably a reason why you have two subsystems today.
But an example of interaction flow (with no detailed knowledge of how your domain is):
GUI calls Application Service CustomerProductService method BuyNewProduct(CustomerDTO customer, ProductDTO newProduct)
CustomerProductService have ICustomerProductRepository and IProductRepository injected into constructor. It will also have a infrastructure Service ICustomerFacadeService (change name now :-)) that is injected into a Property CustomerFacadeService. The creation of this service is done by a factory that have two creation methods, Create() and CreateExtendendedWithCustomerService(). The later one will also inject CustomerServiceFacade
The method BuyNewProduct(...) will now Assemble the CustomerDTO and use the CustomerGUID to load Customer from CustomerFacadeService that will call the web service in the other subsystem.
The loaded customer will ensure that it actually exists but now we load the Product with IProductRepository
With both CustomerGUID value and Product Entity we create a new CustomerProduct entity (which is actually just a mapping class between Products and Customer GUID's) and save it through ICustomerProductRepository
Now you can call another infrastructure service to send an email to your customer that will be notified that it has access to the new product. Or you can create Domain events in CustomerProduct entity that delegates this notification to en eventhandler (in application service layer) that has the IEmailService injected in ctor. Then you have incapsulted the domain knowledge of sending notifications when you connect a new customer to a product.
Hope this help you in modelling your domain with less pain. Because its painful to do DDD. Requires a lot discussions with colleagues, domain experts and yourself in front of the mirror :) Is this the right path?
Look at the DDDsample.net for Domain Events or search for Udi Dahan and domain events.
I write an answer here, more space:
Regarding CustomerAdadpter also refered as CustomerFacadeService in the interaction flow example here is my opinion: How to implement depends of your application. Will most usercase be calling mainsystem calling your "cloud-subsystem" which will have a good uptime: -Then you maybe do not need a queue and will have a WCF service in the cloud. Your CustomerFacadeService will be a service Wrapper that just exposes the method your application layer needs and also assemble all necessary DTO objects.
If your cloud system will also call back to your mainsystem then you need to expose some of your methods as a service. THEN you have the option to expose a NServiceBus endpoint as a WCF service. This gives you the possibility to take down the mainsystem without loosing information.
But there is always a lot of buts...
You need of course to have the WCF service on another machine if your infra-tech guys want to install hotfixes/reboot main system's web server.
If you have client's waiting for an response while main system is down, how long will they wait? Not too long I guess.
So one scenario I can see benefits of this is if you have batches/reports that need to be carried out, and if one part of the system is down, the reporting will continue once it's up again.
Here is some example of NServiceBus exposed as a WCF service. But I have no experience in doing exactly that, just the knowledge of "it can be done".
http://docs.particular.net/nservicebus/architecture/nservicebus-and-wcf

Web Service Contract Design - Single-Responsibility

I'm curious as to see how most developers go about designing the contracts to their web services. I am quite new to service architecture and especially new to WCF.
In short, I'd like to find out what type of objects you are returning in your operations, and does each operation in your service return the same object?
For example consider the following:
Currently, all services I create inherit from a ServiceBase object that looks similar to:
public abstract class AppServiceBase<TDto> : DisposableObjectBase where TDto : IDto
{
protected IAppRequest Request { get; set; }
protected IAppResponse<TDto> Response { get; set; }
}
Response represents the return object which composes something like:
public interface IAppResponse<TDto> where TDto : IDto
{
List<TDto> Data { get; }
ValidationResults ValidationResults { get; }
RequestStatus Status { get; }
}
Therefore, any derived service would return a response composed of the same object.
Now initially, I felt with would be a good design as this forces each service to be responsible for a single object. For the most part this has worked out, but as my services grow, I've found myself questioning this design.
Take this for example:
You have music service you're writing and one of your services would be "Albums".
So you write basic CRUD operations and they pretty much all return a collection of AlbumDto.
What if you want to write an operation that returns the types of albums. (LP, Single, EP, etc)
So you have an object AlbumTypesDto. Would you create a new service just for this object or have your Albums service return many different objects?
I can imagine a complex service with several varying return types to be cumbersome and poor design, yet writing a whole new service for what maybe, only one or two service operation methods to be overkill.
What do you think?
It is a good idea to design your services around your domain problem. By exposing a CRUD pattern on the service, essentially you are using services for data access. The risk of this is your business logic will end up on whatever is consuming your service.
You service should expose methods relavent to the problem you are trying to solve (which loosely models onto the operation on the UI typically)
From here you will see your data contracts start to fit more naturally to the problem you are trying to solve, instead of creating "one size fits all" contracts.
For a good starter, Google "Domain Driven Design" But there is plenty of reference material on this.