Designing WCF data contracts and operations - wcf

I'm starting to design a wcf service bus that is small now but will grow as our business grow so I'm concerned about some grwoing problems and also trying not to YAGNI too much. It's a e-commerce platform. The problem is I'm having too many second thoughts about where to put stuff. I will give a scenario to demonstrate all my questions.
We have an e-commerce website that sells products and ultimately deliveries them. For this we have a PlaceOrder service which, among other parameters, expects an Address object that in this context (our website placing an order) is made of City, Street and ZipCode.
We also do business with partners that use our platform only to sell products. They take care of the delivery. For this scenario we have a PlaceOrderForPartner service that, among other objects, expects an Address object. However, in this context (partner placing an order) the Address object is made of different information that is relevant only to a order placed by partner.
Given this scenario I have several questions:
1) How to organize this DataContracts objects in namespaces and folders in my Solution? I thought about having a folder per-context (Partner, Customer, etc) to keep the services and the DataContracts.
So I would have
- MySolution.sln
- Partner (folder)
- PartnetService.svc
- DataContracts (folder)
- Address
- Customer (folder)
- Customer.svc
- DataContracts (folder)
- Address
Using this way I would have a namespace to place all my context-specific datacontracts.
2) What about service design? Should I create a service for each one that might place and order and create a PlaceOrder method inside it like this:
Partner.svc/PlaceOrder
Customer.svc/PlaceOrder
or create an Order service with PlaceOrderForPartner and PlaceInternalOrder like this:
Order.svc/PlaceOrderForPartner
Order.svc/PlaceOrderForCustomer
3) Assuming that I pick the first option in the last question, what should I do with the operations that are made on the order and common to Partner and Customer?
4) Should I put DataContracts and Service definition in the same assembly? One for each? Everything with the service implementation?
5) How to name input and output messages for operations? Should I use the entities themselves or go for OperationNameRequest and OperationNameResponse template?
Bottom line my great question is: How to "organize" the datacontracts and services involved in a service creation?
Thanks in advance for any thoughts on this!

Besides what TomTom mentioned, I would also like to add my 2 cents here:
I like to structure my WCF solutions like this:
Contracts (class library)
Contains all the service, operations, fault, and data contracts. Can be shared between server and client in a pure .NET-to-.NET scenario
Service implementation (class library)
Contains the code to implement the services, and any support/helper methods needed to achieve this. Nothing else.
Service host(s) (optional - can be Winforms, Console App, NT Service)
Contains service host(s) for debugging/testing, or possibly also for production.
This basically gives me the server-side of things.
On the client side:
Client proxies (class library)
I like to package my client proxies into a separate class library, so that they can be reused by multiple actual client apps. This can be done using svcutil or "Add Service Reference" and manually tweaking the resulting horrible app.config's, or by doing manual implementation of client proxies (when sharing the contracts assembly) using ClientBase<T> or ChannelFactory<T> constructs.
1-n actual clients (any type of app)
Will typically only reference the client proxies assembly, or maybe the contracts assembly, too, if it's being shared. This can be ASP.NET, WPF, Winforms, console app, other services - you name it.
That way; I have a nice and clean layout, I use it consistently over and over again, and I really think this has made my code cleaner and easier to maintain.
This was inspired by Miguel Castro's Extreme WCF screen cast on DotNet Rocks TV with Carl Franklin - highly recommended screen cast !

You start wrong on th highest level.
It should not be "PlaceOrder" service, but "OrderManager". Maybe you want to add more service functions later - like inquiring for orders, cancel orders, change orders - who knows. In general, I would keep the number of "services" (.svc) small and add methods there. Otherwise you end up with a HUGH overhead for using them, in code - without any real benefit.
Why separate between partners and customers? I am sure with 15 minutes of data design, you could break things down to exactly ONE data structure so you could have only one service. If not... make that two methods on one interface, limit by security. But I seriously would NOT like two programs for that. Rather have two address fields - "Address" and "PartnerInfo", and only one can be set (other has to be null), checked in the logic.
Separate out into two projects. Interfaces, data contracts go into a separate project (blabalbla.Api) so that customers can actually get the DLL if they want - at least it makes things a lot easier on your end, you can rely on "shared type", no need to generate the wrappers internally. Allows a lot better testing (as sub-projets dont forget to regenerate the wrappers.... which may lead to errors when testing them).
I always put the implementation into a "blabla.Service" project. Url would be "Services.blabla.com/" in a subdomain (or "api.blabla.com", depends mostly on mood, but lately I am going for api mostly) - separates thigns out from the main website.

Related

Interaction of services in the service layer

What is the best way to organize interaction between services in the service layer?
For example, I have document service and product service. In my case products can have their own documents and to manage documents of product I call appropriate methods from the document service in the product service. So, I need to create instance of document service in product service. And I need to call some methods from product service in the document service too. So, each of these services refers to other and I get stackoverflowexception respectively.
Which design solutions should I use to eliminate these problem?
Application Services are supposed to provide external clients an API for executing cohesive business operations. An application service method generally matches a use case of your application.
While an application service operation may require calling another service (eg, the Create Product use case includes the Create Document use case, which can also be called separately), this is not the norm and you should look to make your application services as cohesive as possible. In particular, just because at some point in your business case you start to manipulate another kind of entity doesn't mean you should delegate that part to another application service - in other words, one application service per entity is not necessarily right.
In any case, from your domain it should appear clearly in which direction the dependency between 2 applications services points. In your example, Product Service seems to depend on Document Service - it's difficult to imagine why it would be the other way around.
If you really need a round-trip between service A and service B (which I wouldn't do unless I have no other option), you could try and have the instance of A inject itself into B instead of relying on a DI container to resolve the dependency with a new instance, solving the stack overflow problem - if that's why you get a stack overflow in the first place.
Obviously, circular dependencies are wrong.
You can use shared identifiers to decouple Products and Documents.
Moreover you can orchestrate the service interaction from outside them, in the application: in the ProductService you can have a LoadProducts(ProductIdentifiers[] identifiers) returning an immutable collection of products and in the DocumentService you can have a LoadDocuments(DocumentIdentifiers[] identifiers) returning an immutable collection of documents.

How to implement .NET code library as a service layer - sharing same BL/CRUD between several applications

Setting: I'm developing an intranet tool set for my department, the main point of which is to centrally manage data quality and accessibility, but also to automate and scale some partial-processes.
Problem: I currently have my business logic in a CLR assembly, which is available on my SQL-Server for other CLR assemblies that run automated ETL directly on the SQL-Server. I am also developing an intranet site, which also needs the code information in that business logic assembly, but referencing the CLR assembly code has been working out sub-optimally, in terms of deployment and code maintenance. Also another department has voiced interest in using the code-base and data for their own intranet site.
Question(s): I've read quite a few Q&A(1,2,3,4,...) on SO to this topic, but I find it a very encompassing, so I'll try to ask questions for a more specific case(i.e. a single BL and Data Access code base)
Is a WCF service the solution I want? All my potential service clients run on the same server, is there maybe another way to reference the same code base both in CLR assembly and website projects? I don't need support for different platforms(ex. Java) - everything is .NET(yay for in-house progr!) - is WCF overkill?
Can code from a WCF service be used like a class library, or do I need to program a new way for accessing classes/methods from the service?
Separation of Development, Test and Productive instances?
Can a WCF service be updated while clients are accessing it, or do I need to schedule maintenance windows? When I update the service, do I need to update the client as well in some way?
Can I dynamically set the service reference, like I currently am dynamically setting the database connection string, depending on if StageConfig = dev, test, or prod?
My CLR assemblies are written for .Net 3.5, but the websites for .NET 4.0, will that pose a problem?
What minimum set of .NET service architecture programming do I need to know to accomplish this? I'll learn more about WCF with time, but I need to evaluate architecting effort and weigh it against getting things done(feature requests). Does the MS tutorial get me the desired skill?
I appreciate answers to only single questions, if you feel you know something, I'll +1 whatever helps me get closer to a complete answer.
OK, so you want to make your code enterprise-wide. There are two fundamental problems to talk about when you want to do this, so I'll structure the answer that way:
You have to understand what WCF is all about.
You have to manage your dependencies correctly.
What WCF is about
WCF is a way of doing RPC/RMI (Remote procedure call/remote method invocation) which means that some client code can call code that is located somewhere else through the network.
A callable WCF service is determined by the ABC triplet:
The service specification is implemented as a .NET interface with a "ServiceContract" attribute. This is the Contract ("C")
The "location" of the service is determined by a pair : Address ("A") and Binding ("B"). The Binding determines the protocol suite to be used for communication between client and server (NetPipe, TCP, HTTP, ...). The Address is a URI following the scheme determined by the Binding ("net.pipe", "net.tcp", "http", ...)
When the client code calls a WCF service at a specific Address, with a specfic Binding, and a specific Contract (which must match what the server at the specific Address and the specific Binding is delivering), WCF generates a proxy object implementing the interface of the contract.
The program delivering the service is any .NET executable. It has to generate one or many WCF Hosts, that will register objects or classes that implement the service contract, and asociate each delivered service to a specific Address and Binding. (possibly many thereof)
The configuration can be through the app .config file, in which you will be specifying ABC triplets and assotiate these triplets with a name that you will use in your application. You can also do it programmatically, which is very easy.
WCF does not address your problem of deploying your application, or the configuration of addresses and binding. It just addresses the problem of letting two executables communicate with each other with strongly-typed objects (through a specific interface). Sharing the service configuration is up to you. You may use a shared .config file on a Windows share, or even set up a LDAP server that will deliver all the data you need to find your service (namely A and B).
Managing your dependencies correctly
In your scenario, there are three actors that want to use your WCF infrastructure:
Your SQLCLR assembly, which will be a client.
The intranet site, which will be another client.
The service host, which will be a server.
The bare minimum number of assemblies will be 4. One for each of the aforementioned actors, and one specifying the contract, which will be used by all three actors. It should contain the following things:
The interface specifying the contract.
All types needed by the interface, which will of course be sent through the network, and therefore must be serializable.
There should be nothing more in it, or else, it will be a maintenance nightmare.
Answer to your questions
I hope that my answer is clear. Let's sum up the answers to your questions.
Is a WCF service the solution I want? All my potential service clients
run on the same server, is there maybe another way to reference the
same code base both in CLR assembly and website projects? I don't need
support for different platforms(ex. Java) - everything is .NET(yay for
in-house progr!) - is WCF overkill?
Everything is overkill. WCF is rather easy to use and scales down very well.
Can code from a WCF service be used like a class library, or do I need
to program a new way for accessing classes/methods from the service?
Setting up a WCF on existing code requires only the implementation of an additional class, and some code creating the Hosts which will serve the aforementioned class.
Calling a WCF service requires the creation of a Channel, which is a .NET (proxy) object implementing the interface.
So basically, your business code remains in the same state.
Separation of Development, Test and Productive instances?
WCF does not take care of that. Different environments, different service addresses. You have to take care of this yourself.
Can a WCF service be updated while clients are accessing it, or do I need to schedule maintenance windows?
It depends on your maintenance policy. Kill the serving process and launch the new version is the basic upgrade mechanism.
When I update the service, do I need to update the client as well in some way?
Provided that you manage your dependencies correctly like I sketched in the previous section, you need to update the clients only if the service specification (the interface) changes.
Can I dynamically set the service reference, like I currently am dynamically setting the database connection string, depending on if StageConfig = dev, test, or prod?
You have to manage that, probably by etting Address and Binding for a service programmatically.
My CLR assemblies are written for .Net 3.5, but the websites for .NET 4.0, will that pose a problem?
Provided that you manage your dependencies correctly like I sketched in the previous section, the only constraint will be the minimum CLR version required by the "contract" assembly.
What minimum set of .NET service architecture programming do I need to know to accomplish this? I'll learn more about WCF with time, but I need to evaluate architecting effort and weigh it against getting things done(feature requests). Does the MS tutorial get me the desired skill?
You'll need the result of these exercises:
Make two executables, a client and a server, that will communicate
through a WCF contract located in a separate DLL. The configuration
should be located in the app .config file.
Make two executables, a client and a server, that will communicate
through a WCF contract
located in a separate DLL. The configuration should be determined programatically.
Try to send a serializable class as a parameter to your service.
Try to send a serializable class as a return value of your service.
After that, you'll need to think about the best/cheapest way to share the Addresses and Bindings of your services.
Hope it helps.

Multiple services vs unique service

Hi i would like your help so i can decide on what to do with this matter. The thing is that at my work we are currently migrating from Web Services to using WCF, now the thing is that when we used web services we had one web service that was in charge of invoking the business logic now the thing is that i would like to know what is actually the best way to achieve the same functionallity with WCF, using one unique service to call the different business logic classes or have multiple services to call the different business logic classes? also i have to clarify that when i say one unique service i mean that this will have just one method that one way or another will be capable of invoking any of the business logic classes depending on certain parameters and will also have other methods but for other different tasks, now i would like to know which would be the best approach for this, by the way the reason we have consider using one service like i told you is to manage from there the commits or rollbacks necessaries when something blows when making an operation on the db and have it just from one place, not all over the place, thanks in advance and well i'm kind of new with wcf.
You can migrate your existing service structure into WCF and still have the same functionality. You'll need to create and expose the service(s) according to WCF, but the architectural structure can remain how you have it in Web Services. You may want to revisit your design. There are many features at your disposal, including Entity Framework, that allow you to manage commits, rollbacks, etc.

Accessing Domain Driven Design Class LIbraries from a WCF Service

I need some help clarifying how I should be setting up my project. My solution structure is as follows:
Company.DataTransferObjects
--AdminDTO.cs
--CustomerDTO.cs
Company.DataTransferObjects.Helpers
Company.Infrastructure.DomainServices
--Admin
---AdminService.cs
--Customer
--CustomerService.cs
Comapny.Infrastructure.Repositories
--Admin
---AdminRepository.cs
--Customer
---CustomerRepository.cs
Company.Domain
--Admin
---Admin.cs
---IAdminRepository.cs
--Customer
---Customer.cs
---ICustomerRepository.cs
Company.WebServices
--WebApi.cs
--IWebAPI.cs
My questions are as follows:
1) Does my set-up look right to you?
2) DTOs. From the web service's perspective, where should the DTOs be created?
Should I be creating the DTOs in an independent class library and referencing
them from the WebService or should they be part of my web service project?
Also, it is not clear to me how my DTOs should be interacting with my Domain objects.
Can somebody please explain their purpose from a program flow point of view and, specifically, if you were creating a WCF service how you would be manipulating them?
3) Domain Services. I am still having a hard time wrapping my mind around the purpose of Domain Services. Is this what is exposing the operational functionality that is not hitting the database and requires repository methods that cannot be accessed directly?
In other words, is a Domain Service a method that manipulates multiple repository methods? So, if my WCF service is calling data that can be accessed via a repository method, then that is what it should do. But, if it requires data that is the result of multiple repository methods, then this should be done via domain services?
4) Where does the Facade Pattern fit in a the DDD architecture?
Please excuse my confusion, I am trying to understand. It would be a serious help if you could tell me "what" I should be accessing from my WCF service.
Thanks!
going in reverse order on your questions:
4) Your web services are a facade to your domain, effectively.
3) Domain services can hit the DB too, they're typically the main API that consuming code should use to talk to your domain on anything that involves more than a single entity, or for things that represent a series of transactional steps. Some folks consider Repositories to be a special case of Domain Services (Rather than being an either/or). I usually consider my Services to be my domain's public interface.
2) DTO's are normally useful when you are (or plan to eventually) crossing physical boundaries. Anytime you think you might need to serialize something (e.g. into a SOAP message), you want to think about a DTO. SO in your case, your WCF project would use DTOs as its DataContracts, but internally it might use your domain objects (unless you expect your domain to sit in a different app domain or on a different physical box).
1) It's all personal preference; your layout doesn't look unreasonable, though it's different than how I normally organize.

Simpler Explanation of How to Make Call WCF Service without Adding Service Ref

In Understanding WCF Services in Silverlight 2, the author, David Betz, explains how to call a web service without adding a service reference in the client application. I have a couple of weeks experience with WCF, so the article was over my head. In particular, although the author gave a lot of code snippets, but does not say what goes where. In the article, he provides two different code snippets for the web.config file, but does not clarify what's going on.
Looking at the source code there are four projects and two web.config files.
So far, I have been using the standard Silverlight project configuration of one project for the web service and one for the Silverlight client.
Firstly, does the procedure described in the article work with the standard two project configuration? I would think it would.
Secondly, does anyone know of a simpler example? I am very interested in this, but would like to either see source code in the default two project setup which is generated when a new Silverlight project is made, or find a step by step description of how to do this (eg, add a class called xxx.cs and add this code..., open web.config and add these lines...)
Many thanks
Mike Thomas
First, a little philosophy...
If you are a consumer of a WCF service that you did not write, adding a service reference to your client is really the only mechanism you have to enable interaction with that WCF service. Otherwise, you have no way of knowing what the service contract looks like, much less its data and message contracts.
However, if you are in control of both the client and the WCF service itself, adding a service reference to the client is a nice convenience, but I've recently been convinced not to use it. For one, it becomes a nuisance after the first few times you change your contract to remember to update your service reference. And in my case, I have several different C# projects that are consuming the WCF service, so I have to remember to update each one of them. Second, creating a service reference duplicates the contract definitions that are already defined in your WCF service. It is important to understand the implications of this.
Let's say your WCF defines the following type.
[DataContract]
public class Person
{
[DataMember] public string FirstName {get; set;}
[DataMember] public string LastName {get; set;}
}
When you add a service reference to your client, the metadata associated with this class is retrieved through the metadata exchange (MEX) endpoint, and an exact replica of this class is created on the client side that your client "compiles" against. So your WCF service has a definition of the Person class, and so does your client, but they are two different, distinct class definitions.
Given this, it would make more sense to abstract the Person class into a separate assembly that is then shared between the WCF service and the client. The added benefit is that when you change the contract definitions within this shared assembly, you no longer have to update the service reference within the client because it is already referencing the shared assembly. Does that make sense?
Now to your question. Personally, I've only used WCF within C# projects, not Silverlight. However, I do not think things are radically different. Given that, I would suggest that you watch the Extreme WCF video at dnrTV. It gives a step-by-step guide for how to bypass the service reference feature.
Hope this helps.
Let me try - I'm not an expert at Silverlight development, so bear with me if I say something that doesn't apply to Silverlight :-)
As Matt Davis mentioned, the "usual" use case is this: you add a service reference to a given service URL. In doing so, Visual Studio (or the command-line tool svcutil.exe) will interrogate the service and grab its metadata - information that describes the service, all the available methods to call, what parameter they expect etc. From this, it will generate a class for you (usually called the "client" or "client proxy"), which you as a client (=service consumer) will use to call the service. You can have this client proxy class generated inside your "normal" Silverlight client project, or you could possibly create your own "service adapter" class library, esp. if you will be sharing that client proxy code amongst several Silverlight projects. How things are structured on the server side of things is totally irrelevant at this point.
As Matt D. also mentioned, if you do it this way, you're getting copies of the service, its methods, and its data, in your client - those are identical in structure to what the server has - but they're not the same type - you on the client side have one type, the server has another (the fields and properties are identical though).
This is important to remember since the whole basic idea of WCF is message-passing - all that connects the client (you) and the server (the other end) are the messages and their structure - what method to call and what values to pass into that method. There's no other link - there's no way a server can "connect" to the client code and check something or whatever. All that gets exchanged is serialized messages (in text or binary form).
If you do control both ends, you can simplify things a bit - you can physically share the service contract (the definition what the service looks like and what methods it has to call into) and the data contract (the description of what data is being passed back and forth) on both the server side as well as the client side. In this case, you won't be adding a service reference, you won't be duplicating the service and data definitions, so things are a bit easier (but it only works if you're in control of both ends).
In this case, best practice would be to package up all that describes the service (the service interface with its methods and the data contracts) into a separate assembly (class library) on the server, which you can then copy to the client side, and reference directly from there (like any old assembly you might have). So in this case, you would typically have at least three projects in your solution:
your actual Silverlight client project
the website or web app hosting your Silverlight control for testing
the service interface assembly, which contains the service and data contracts
So there you have it - I hope I covered all the basics of what's going on, and why you would want to do one or the other thing. If you need additional info, don't hesitate to comment on this posting and let us know!
Marc