It was my understanding that when a developer (a company) develops both client and service, it’s better to put data and service contracts into a separate assembly to be used by both client and service applications. It is to avoid code duplication while generating a proxy classes using e.g. svcutil.
Is this indeed the preferred approach and have you ever had a project that was an exception from this rule?
We do this all the time in our projects and i don't know what can be said against that approach.
Sharing contract assembly can lead to unwanted dependencies, since these contract classes such as datacontract\servicecontract can contain methods. These methods then can get called transparently in client\server code hence breaking the encapsulation of these contracts. Data\Service contracts are meant to be used only as an mechanism to share data.
Related
I am currently in the process of developing a Web Service which should expose a relatively large number of ways to interact with it.
For example, Clients may be able to interact with the Web Service in order to manage users or projects in a Database.
To that effect, I created the following classes:
Two Data Contracts: IUsersServiceContract and IProjectsServiceContract
Two Service Contracts Interfaces: IUsersServiceContract and IProjectsServiceContract
My question is the following:
Does it make sense to create two different Web Services, each with their own endpoint(s), instead of creating one big class that implements both Service Contracts Interfaces ?
Keep in mind that in reality I would have many more Service Contracts Interfaces that deal with different sorts of data.
From what I understand, using a partial class (split in multiple files) will allow me to create one big Web Service with only one Endpoint.
This has the disadvantage of dealing with one big class split in multiple files, i.e: its harder to maintain and more prone to errors if developers "don't see the big picture".
The other solution would be to have one Web Service per Service Contract Interface implemented.
In essence, if I have X Service Contracts Interfaces, I end up with X Web Services with X Endpoints.
Which solution would you choose and why ?
Thanks for your input !
Personally I would not use partial classes for splitting a class; the sheer size motivating tgis split suggests that the class is too large and needs a refactoring. In my opinion partial classes main purpose is to add changes to auto generated code.
Since service and endpoint configuration can be shared using named behaviours in web.config splitting the service should not be that cumbersome. But the split should be motivated by grouping of functionality.
Without knowing the exact nature of you services it sounds like there could be a natural separation in two services; one for user related operations and one for project oriented operations.
If the implemantation classes grows above what you think are reasonable sizes I would consider letting separate classes - or preferably interfaces - handle each methods inner logic and let the service implementation it self be a shallow facade that delegates its own method parameters to the correct logoc instance
An important thing to consider here, when you're talking about n number of service contracts, is the cost associated with implementing each service contract. There's a good blog post on that here, "Service Contracts Factoring and Design", although if it wasn't Juval Lowy who posted this article then someone is clearly ripping him off (I am referring to Juval's book - "Programming WCF Services" page 93).
Just personal style, I guess, but I hate having 2 files for my WCF Services. I tend to like to copy/paste the interface into the .cs file so that I only have to deal with a single file.
Any dangers in doing this?
Not dangers per se - but there are times when it is very useful to have a separate assembly with your service, operation and data contracts (just the contracts, the interfaces, basically) - when you need to share those between the server and the client side.
There's really no point in sharing the whole service implementation code (the actual service class, that implements the service interface), with the client.
Plus: if you have your interfaces in a separate file (and possibly assembly), it makes it easier to write unit tests, especially if you want to mock a service. Gets a bit messy if you mix interface and class into a single file.
So I consider it a useful and helpful best practice to have separate files for interfaces and implementations (actually: always one class per file only), and to put all service- and data contracts (and fault contracts) into a separate assembly.
Actually, I like to go beyond two files, and have two separate projects. One project holds the interface definition. The primary value is for integration testing. I like to make a third project with a WCF client. That client accesses the interface in the "shared" assembly.
Remember the mantra of Testivus: "When writing the (production) code, think of the test; When writing the test, think of the code."
I have a self hosted TCP based WCF service. I am now building a project that consumes that service, but there seems to be at least two ways of adding a service reference to a project and the both produce wildly different proxies. First I used the "Add service reference" from the project menu, but this generated quite a few files and even some XML schemas of the core .Net types. Then I tried the SvcUtil which only produced two files, one proxy and one config file that holds the service reference and binding parameters, this is much better but...
In both cases the VS tools seem to reproduce type definitions even though I have provided a reference to the assembly containing the service and all the types it uses. For example, some of my service methods return generic collections of Entity classes. All the Entity classes are defined within an assembly that I have directly referenced from the consuming project so why redefine those types again?
I would be grateful if some body could offer some advice on consuming WCF services that return Entity types and any best practices they follow.
We have found that the add service reference creates alot of unneeded code that gets in the way more than it helps.
We have gone over to a manual way of setting it up, there is an introduction to this method here:
http://perseus.franklins.net/dnrtvplayer/player.aspx?ShowNum=0103
Yes, in your concrete case this may seem like duplication - but consider this: WCF is also designed to be interoperable, and in MOST scenarios, especially if you have a non-.NET client calling your code, you won't have the assembly with the contract and the interfaces available.
So there's really nothing BUT creating a full proxy, that contains all that information, in order to work in all possible circumstances.
Now if you really want to avoid duplication of data contracts etc., you can compile those into their own assembly, and then use the /r:(assembly name) switch when calling svcutil to tell it to re-use the code and contracts in that assembly.
Marc
WCF promotes good design by using interfaces and contracts etc. What baffles me is that, for example in my case if I have 2 sets of business functionality like ICustomerMgmtBIZ
and IProductMgmtBiz. If these two are ServiceContracts, and I have an interface like
IBusinessService:IProductMgmtBIZ,ICustomerMgmtBIZ
and implementation class BusinessService. I see that BusinessService class will be having too much implementation. The workaround I have been using so far is by implementing partial classes.
So bluntly put, can a WCF service have only 1 implementation and 1 service contract ??
No, it is possible to implement more than one Service contract on a WCF Service type (the class that is attributed with the ServiceBehavior attribute), since it is just a matter of having the class implement multiple interfaces. If you are using any of the Visual Studio templates or other kinds of code generators, this may not be immediately clear. However, although you can implement more than one Service Contract interface on a Service type, it does not do you much good if you need the service, presumably a singleton in this case(?), to behave as one service. IBusinessService implies that you need all of the service's functionality to be callable from one client proxy, so that all operations may operate in the same logical session (similar to ASPX web session). If that is not the case, then you are free to define individual proxies for each contract interface, but that will also require that you support one endpoint for each contract.
Is it an absolute requirement that you can only have on WCF ServiceHost instance for your implementation? What factors are influencing your decision?
By the way, partial classes do not trouble me anymore. The idea of splitting out code into multiple files now seems rather natural. For example, storing partial classes in files like ServiceType_IProductMgmtBiz.cs and ServiceType_ICustomerMgmtBIZ.cs seems natural enough, in addition to storing the core logic in ServiceType.cs.
Finally, the following question might be of use...
WCF and Interface Inheritance - Is this a terrible thing to do?
Bluntly put, no - sort of - yes, but. Any workaround is non-optimal and involves using an "IBlank" as a master WCF interface (where your interfaces derive from IBlank), and two endpoints, one implementing IProductMgmtBIZ and the other implementing ICustomerMgmtBIZ. I don't have my dev machine in front of me, this might involve some other overrides. So, at the WCF level you're screwed unless you want to have two WCF ServiceHosts (which is perfectly reasonable).
In short, the workaround is inelegant. Its easier to have two WCF endpoints on the same port with a different extension.
I've noticed that a handful of WCF applications choose to "break" their objects apart; that is, a project might have a DataObjects assembly that contains DataContracts/Members in addition to a meaningful class library that performs business logic.
Is this an unnecessary level of abstraction? Is there any inherent evil associated with going through and tagging existing class libraries with DataContract information?
Also, as an aside, how do you handle error conditions? Are thrown exceptions from the service (InvalidOperation, ArgumentException and so on) generally accepted, or is there usually a level around that?
The key reason to separating internal business objects from the data contracts/message contracts is that you don't want internal changes to your app to necessarily change the service contract. If you're creating versioned web services (with more than 1 version of the implemented interfaces) then you often have a single version of your apps business objects with more than 1 version of the data contract/message contract objects.
In addition, in complex Enterprise Integration situations you often have a canonical data format (Data and Message contracts) which is shared by a number of applications, which forces each application to map the canonical data format to its internal object model.
If you want a tool to help with the nitty gritty of separating data contract/message contract etc. then check out Microsoft's Web Services Software Factory http://msdn.microsoft.com/en-us/library/cc487895.aspx which has some good recipes for solving the WCF plumbing.
In regards to excpetions, WCF automatically wraps all exceptions in FaultExceptions, which are serialized as wire-format faults.
It's also possible to throw generic Fault Exceptions which allows you to specify additional details to be included with the serialized fault. Since the faults thrown by a web service operation are part of its contract it's a good idea to declare the faults on the operation declaration:
[FaultContract(typeof(AuthenticationFault))]
[FaultContract(typeof(AuthorizationFault))]
StoreLocationResponse StoreLocation(StoreLocationRequest request);
Both the AuthenticationFault and AuthorizationFault types represent the additional details to be serialized and sent over the wire and can be thrown as follows:
throw new FaultException<AuthenticationFault>(new AuthenticationFault());
If you want more details then shout; I've been living and breathing this stuff for so long I almost making a living doing it ;)