Web service coordination - wcf

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.

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.

WCF Service and Business Logic

I am unsure where to place my business logic. I have a WCF service which exposes its methods to my client.
Should my business logic go in the service method
public User GetUser(int id)
{
//Retrieve the user from a repository and perform business logic
return user;
}
or should it be in a separate class where each WCF service method will in turn call the business layer methods.
public User GetUser(int id)
{
return _userLogic.GetUser(id);
}
My personal preference is to have WCF as a very thin layer on top of a separate business layer. The WCF layer does nothing more than make calls to the business layer, similar to what you have shown in option 2. This gives you some flexibility in the event that you want to have your business layer consumed by something other than WCF clients (for example, a WPF application calling your business layer directly rather than via WCF).
WCF services are already, by default, designed for reuse. I see no reason not to have some logic in your services, though keep in mind things like the Single Responsibility Principle so you don't end up with a service that does a dozen things.
Even then, if you end up parceling out your functionality into smaller classes, it's not a bad idea at all to host those classes as WCF services. You can then use them in-proc (via pipes) when needed or across machine boundaries (tcp) or even as web services. Create facades as needed to provide access to the functionality of your other, smaller services.
There's no real need to avoid putting any logic in WCF service classes.
I think that the decision depends on your business needs. WCF is a mechanism to transport data (objects) between server and client. If you like your businsess logic runs on server, you should let WCF exposes the object after running your business logic.
It should go in a separate set of classes. Your WCF layer should only contain logic that directly pertains to how the product of the service is delivered.
In your case, I see that you have a WCF method that returns a User (I assume this is a custom class) why have a separate method to return the UserID instead of populating that property as part of returning the User object?
For reuse/testability/maintenance/readability you should always put you BL in a separate layer.

Utilizing multiple service contracts over the same WCF channel or session

I'm in the process of writing a duplex WCF service using NetTcpBinding, and I've run into an architecture question that I think I know the answer to, but hope that I'm wrong.
Our service is stateful, and we've selected NetTcpBinding with PerSession InstanceContextMode. For various reasons, this is something that we require. I'm trying to break up our larger interface (where large blocks of the operations would not apply to many clients) into multiple smaller interfaces with the operations logically grouped. While it's simple enough to have a single service implementation implement all of the contracts, I'm not sure if it's possible to have multiple service contracts share a single channel (or, more to my requirement, a single session), and I'd definitely need to be able to do that in order to make this work.
I could, of course, include everything on one contract and throw FaultExceptions when an invalid operation is performed, but I'd really like to be able to break these up and not even add an endpoint for inapplicable contracts. Is what I'm looking for possible?
TL;DR Version:
I need to be able to do this:
[ServiceContract]
public interface IServiceA
{
[OperationContract]
void Foo();
}
[ServiceContract]
public interface IServiceB
{
[OperationContract]
void Bar();
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class Service : IServiceA, IServiceB
{
...
}
And be able to establish one session from the client to the service but use both IServiceA and IServiceB.
The default instance provider over a sessionful channel will give you an instance per connection in your case. You can however extend the instance provider to pick up an existing object from your own cache and return the same object.
How you correlate instances will be upto you using some special message header etc. The underlying channel/Connection will be different for each proxy and also use differnt buffers / concurrency models but you can allow service model to use the same instance.
http://msdn.microsoft.com/en-us/magazine/cc163590.aspx

WCF Multiple Interface

i am really wanting to get my head around this WCF technology and it seems the last months of information cramming has somewhat distorted my overall concept of how i should build my client/server application.
If someone out there could shed some light on the best practises when developing my app and implementing a Duplex WCF service with multiple interfaces.
General outline: I am wanting to develop an app where users connect to a server and lets say'.. add contacts to an sql database. I have discovered many ways of doing this but would ultimatly like to know im heading down the right path when it comes time to developing the app further.
Some models i have discovered are...
Client has its own LINQ to SQL classes and handles all data to and from data.... BAD. really slow. overheads with LINQ and SQL connections amongst poor implementation of Linq Select command.
Another model was the develop the service to implement the linq to sql commands which are used for CRUD operations however this still doesnt provide live data updates to other clients connected to the service.
So i made a basic app that when a client logs in the to the service there Callback Channel gets added to the Callback List. When a client feeds in a new contact to the service, it invokes a callback to all channel clients with the new contact and the client side function takes care of adding the contact to the right spot.
So now i want to implement a User object and perhaps 2 more other business objects say Project and Item and lets say Item... my idea is to create my service like this
[Serializable]
[DataContract]
[ServiceBehavior(
ConcurrencyMode = ConcurrencyMode.Single,
InstanceContextMode = InstanceContextMode.PerCall)]
public class Project: IProject
{
[DataMember()]
public int projectID;
public int Insert(objSubItem _objSubItem)
{
// code here
}
etc and
[ServiceContract(
Name = "Project",
Namespace = "",
SessionMode = SessionMode.Required,
CallbackContract = typeof(IProjectCallback))]
public interface IProject
{
/// <summary>
/// Inserting a Project record to the database
/// </summary>
/// <param name="_project">Project from Client</param>
/// <return>ProjectID back to the client if -1 then fail</return>
[OperationContract()]
int Insert(Project _project);
and
public interface IProjectCallback
{
/// <summary>
/// Notifies the clients that a Project has been added
/// </summary>
/// <param name="_project">Inserted Project</param>
[OperationContract(IsOneWay = true)]
void NotifyProjectInserted(Project _project);
}
obviously i have other crud functions and functions to ensure that both client and server data records are read only when being editited.
now if i have multi objects what is it the best way to lay it out.
Im thinking to create a servce.cs and an Iservice.cs and an IserviceCallback to negotiate the client channel population.. sould i also use partial classes of the service to implement the Iproject and IUser to properly ivoke the service callbacks aswell as invoking the objects insert.
would i do it like this
[ServiceContract(Name = "Service",
Namespace = "",
SessionMode = SessionMode.Required,
CallbackContract = typeof(IServiceCallBack))]
[ServiceKnownType(typeof(Project))]
[ServiceKnownType(typeof(User))]
public interface IService
{
// code here
}
and also
[ServiceBehavior(
ConcurrencyMode = ConcurrencyMode.Single,
InstanceContextMode = InstanceContextMode.PerCall)]
public partial class Service : IUser
{
public int Insert(User _User)
{
//
}
}
public partial class Service : IProject
{
public int Insert(Project _project)
{
// code here
}
}
public partial class Service : IService
{
// functions here
}
}
if feels as though the approach feels right if it was for one interface but feel that i need some "Best Practice" assistance.
Many thanks in advance,,
Chris Leach
Hi Richard,
I appreciate your response. As you see this is my first post and third ever on any forum related to programming. I have lived my programming life very close to google as shown by my google autofill history but its time to start asking questions of my own so i thank-you for your assistance so far. I am really wanting to understand an overall approach to how best managing data consistency amongst a distributed client/service application. I am looking into Telerik ORM and also Entity Framework as a solution and exposing the entities through a WCF service but i lack the understanding to implement data consistency amongst the clients. i have managed to develop a netDualTcp chat application and have used a list of client callback context to send join/leave and chat functions. I lack the overall picture however it seems that if i have a in memory (static) version of all of the tables in my sql database and either have the clients bind directly to these lists if this is possible or it seems best for my custom user controls to handle the connections so the server is aware of who has that particular user control open and can direct changes to those clients who are registered to the callback contract. that way the clients arent having to load the entire project every time they wish to open the application. I am thinking of a multi purpose application such as a contact/grant application program where users will be using different parts of the application and do not always need to access all of the information at one time. When the user first logs in i am hoping that the service will attach a callback contract for the client and several bits of information are loaded back to the client on authentaction such as a basic state i.e if they are an admin they get notifications etc. once they are logged in they are presented with a blank canvas but then begin to load custom user controls into a docking panel type interface. i guess this is where i become a little stuck about how to best manage concurrency and consistency whilst minimizing load/data transfer times to the client and freeing up cpu proccess time on both client. I know in programming there are multiple ways of doing this but i would like to know from the people on this forum what they feel the best approach to this type of soultion is. I understand its a deep topic but i feel i have come this far and a guiding hand would be appreciated. Thanks again
Generally I find taking a non-abstract view of a service gets me to the right place. What is it that consumers of my service are going to need to do?
I obviously have internal domain objects that are used by my business layer to create and manipulate the data. However, the way the business layer does tings isn;t necessarily the best way to partition functionality for my service.
So for example, if any project should have at least one user in it then when you create the project you should send over at least one user at the same time. The service operations need to encapsulate all of the data required to carry out a self contained business transaction.
Similarly, the death knell of many distributed systems is latency - they require lots of round trips to complete something. So, for example, you want to be able to add a user to a project; in reality you probably want to add a number of users to as project. Therefore, you should model the operation to accept a list of users not a single one which must be invoked multiple times
So a project service should allow you to do all the things related to a project, or projects, through a service contract. If users can live independently of projects then also have a user service. If they cannot then don;t have a user service as everything needs to be project focussed.
Business transactions are often more than straight forward CRUD operations on domain entities and the service should model them rather than reflecting the data model

Need some advice for a web service API?

My company has a product that will I feel can benefit from a web service API. We are using MSMQ to route messages back and forth through the backend system. Currently we are building an ASP.Net application that communicates with a web service (WCF) that, in turn, talks to MSMQ for us. Later on down the road, we may have other client applications (not necessarily written in .Net). The message going into MSMQ is an object that has a property made up of an array of strings. There is also a property that contains the command (a string) that will be routed through the system. Personally, I am not a huge fan of this, but I was told it is for scalability and every system can use strings.
My thought, regarding the web services was to model some objects based on our data that can be passed into and out of the web services so they are easily consumed by the client. Initially, I was passing the message object, mentioned above, with the array of strings in it. I was finding that I was creating objects on the client to represent that data, making the client responsible for creating those objects. I feel the web service layer should really be handling this. That is how I have always worked with services. I did this so it was easier for me to move data around the client.
It was recommended to our group we should maintain the “single entry point” into the system by offering an object that contains commands and have one web service to take care of everything. So, the web service would have one method in it, Let’s call it MakeRequest and it would return an object (either serialized XML or JSON). The suggestion was to have a base object that may contain some sort of list of commands that other objects can inherit from. Any other object may have its own command structure, but still inherit base commands. What is passed back from the service is not clear right now, but it could be that “message object” with an object attached to it representing the data. I don’t know.
My recommendation was to model our objects after our actual data and create services for the types of data we are working with. We would create a base service interface that would house any common methods used for all services. So for example, GetById, GetByName, GetAll, Save, etc. Anything specific to a given service would be implemented for that specific implementation. So a User service may have a method GetUserByUsernameAndPassword, but since it implements the base interface it would also contain the “base” methods. We would have several methods in a service that would return the type of object expected, based on the service being called. We could house everything in one service, but I still would like to get something back that is more usable. I feel this approach leaves the client out of making decisions about what commands to be passed. When I connect to a User service and call the method GetById(int id) I would expect to get back a User object.
I had the luxury of working with MS when I started developing WCF services. So, I have a good foundation and understanding of the technology, but I am not the one designing it this time.
So, I am not opposed to the “single entry point” idea, but any thoughts about why either approach is more scalable than the other would be appreciated. I have never worked with such a systematic approach to a service layer before. Maybe I need to get over that?
I think there are merits to both approaches.
Typically, if you are writing an API that is going to be consumed by a completely separate group of developers (perhaps in another company), then you want the API to be as self-explanative and discoverable as possible. Having specific web service methods that return specific objects is much easier to work with from the consumer's perspective.
However, many companies use web services as one of many layers to their applications. In this case, it may reduce maintenance to have a generic API. I've seen some clever mechanisms that require no changes whatsoever to the service in order to add another column to a table that is returned from the database.
My personal preference is for the specific API. I think that the specific methods are much easier to work with - and are largely self-documenting. The specific operation needs to be executed at some point, so why not expose it for what it is? You'd get laughed at if you wrote:
public void MyApiMethod(string operationToPerform, params object[] args)
{
switch(operationToPerform)
{
case "InsertCustomer":
InsertCustomer(args);
break;
case "UpdateCustomer":
UpdateCustomer(args);
break;
...
case "Juggle5BallsAtOnce":
Juggle5BallsAtOnce(args);
break;
}
}
So why do that with a Web Service? It'd be much better to have:
public void InsertCustomer(Customer customer)
{
...
}
public void UpdateCustomer(Customer customer)
{
...
}
...
public void Juggle5BallsAtOnce(bool useApplesAndEatThemConcurrently)
{
...
}