问题
This is a question I got asked in an interview.
When you create a WCF service, you get two files; "IService.cs" and "Service.cs". Why is it a class implementing an interface versus a class inheriting an abstract class. Don't reply saying that you cannot put a [servicecontract] attribute over the abstract class. I know you can only apply it to interfaces, but why?
回答1:
One can implement more than one interface. One can only inherit a single abstract class.
回答2:
WCF completely decouples the client from the service, if you specify the implementation of the service as the service you have tightly coupled your client to the service.
回答3:
Several reasons I can think of:
- A clear statement of intent - "this set of API signatures is totally decoupled from any possible implementation". By contrast, an abstract class (in my opinion) is more a statement of "this base class was designed to work with this set of derived classes".
- More open for modification - once you inherit one base class, that's it. Since a
[ServiceContract]
has no implementation, why waste the one inheritance slot you have on it? For example, all our service classes inherit from an abstractServiceBase
class which provides common context state and methods, in addition to implementing the[ServiceContract]
interface. However, even if that were not the case, I would still leave the base class slot free for future use. - It permits one service class to implement more than one
[ServiceContract]
if appropriate. - If you are using a strict contract versioning system that relies on inheriting one
[ServiceContract]
from another, then adding service classes to the same inheritance tree will ruin it.
来源:https://stackoverflow.com/questions/8564710/why-do-wcf-services-use-interfaces-as-a-service-contract-instead-of-an-abstract