我有一些在整个系统上使用的现有接口.
现在我想使用其中一个接口作为服务合同.
但问题是我需要在现有接口上添加[ServiceContract]和[OperationContract]属性,它们会污染其余的代码.
没有重复接口的任何解决这个问题的方法?
在具体实现上应用属性?这是一个很好的做法吗?
谢谢
您可以使用service-warpper类型接口扩展接口,即:
public interface IMyCode
{
string GetResult();
}
[ServiceContract]
public interface IMyCodeService : IMyCode
{
[OperationContract]
string GetResult();
}
Run Code Online (Sandbox Code Playgroud)
C#允许接口继承,编译器会发出一个IMyCodeService.GetResult需要new 的警告,因为它隐藏了IMyCode.GetResult方法,但不附加new不会破坏实现,例如:
class Program
{
static void Main(string[] args)
{
MyCodeService service = new MyCodeService();
IMyCodeService serviceContract = (IMyCodeService)service;
IMyCode codeContract = (IMyCode)service;
service.GetResult();
serviceContract.GetResult();
codeContract.GetResult();
Console.ReadKey();
}
}
public interface IMyCode
{
void GetResult();
}
public interface IMyCodeService : IMyCode
{
void GetResult();
}
public class MyCodeService : IMyCodeService
{
public void GetResult()
{
Console.Write("I am here");
}
}
Run Code Online (Sandbox Code Playgroud)
这样,您可以根据现有界面提供服务合同,而无需更改现有代码.
如果您共享合同程序集而不是使用WCF为您生成代理,您甚至可以在您接受现有接口的地方传递服务合同,因为服务接口继承了它.