Today I began toying with WCF. One thing I noticed is that, by default, Visual Studio defines a WCF service in terms of a ServiceContract
, which is an interface; and a class actually implementing that interface. However, in this article, I found the following snippet (what the code actually does is irrelevant):
[ServiceContract]
public partial class BookmarkService
{
// in-memory resource collections
Dictionary<string, User> users = new Dictionary<string, User>();
Dictionary<string, Bookmark> bookmarks = new Dictionary<string, Bookmark>();
[WebGet(UriTemplate = "users/{username}")]
[OperationContract]
User GetUserAccount(string username)
{
// ...
So, is 开发者_运维知识库it necessary to separate a WCF Service's interface from its implementation? If it is not strictly necessary to do that, does it offer any advantages versus not doing it?
It is not strictly necessary to separate out the service contract as an interface - as you've seen.
But it's highly advisable to do so:
- you get more flexibility
- you get better testability
WCF services are perfectly suited for using interfaces to define the contract which the service guarantees, and separating that from the actual implementation.
Also, with having contracts as interfaces, you can have a single service implementation class implementing several service interfaces - yet another degree of flexibility.
精彩评论