【问题标题】:C#: Inheriting one interface to another that will act as a wcf interfaceC#:将一个接口继承给另一个将充当 wcf 接口的接口
【发布时间】:2012-07-27 09:46:52
【问题描述】:

我已经问了一些与此相关的问题,但仍然没有确定的答案,所以这里有一个更简单的问题。

考虑一下。我有2个接口。一个描述一个道。一种是 wcf 接口。 wcf 接口继承了 dao 接口,以便使用 wcf 属性公开其方法。因为它是一个 wcf 接口,所以我当然必须再次声明这些方法,以便在它们上放置 wcf 属性,例如 [OperationContract]。结果,我实际上隐藏了以前的接口方法,并且必须在它们上放置“新”关键字。在这种情况下这样做是否正确。我需要能够通过 wcf 接口呈现 dao 接口方法,因此是继承它的原因。我想强制 wcf 接口公开这些功能。看来我的手很紧,我必须使用这种方法才能暴露这些方法,但你怎么看?

在代码方面它看起来像这样:

//The dao interface
public interface IMyDao
{
    void Foo();
}

//The wcf interface which implements/extends the IMyDao interface in order to add wcf attributes
[ServiceContract]
public interface IMyWCF : IMyDao
{
    [OperationContract]
    new void Foo();
}

//The dao class that implements the dao interface
public class MyDao : IMyDao
{
    public void Foo()
    {
        //Do something
    }
}

//The class implements the wcf interface. Makes calls to the dao.
public class MyWCF : IMyWCF
{
    public void Foo()
    {
        MyDao myDao = new MyDao();

        myDao.Foo();  
    }
}

【问题讨论】:

    标签: c# inheritance interface method-hiding


    【解决方案1】:

    使用 2 个接口 - 不要为 DAO 和 WCF 合约共享一个接口

    包括一个将 WCF 服务调用传递给 DAO 的包装器。

    例如,如果你的 DAO 有以下方法:

    public interface IMyDAO
    {
        MyObject GetMyObjectById(int Id);
    }
    

    您的运营合同将具有相同的签名:

    public interface IMyWCFContract 
    {
        [OperationContract]
        MyObject GetMyObjectById(int Id);
    }
    

    然后你会有一个包装类:

    public class MyWCFService : IMyWCFContract
    {
         private MyDAO dao;
    
         public MyWCFService()
         {
            dao = new MyDAO(); 
         }
    
         public MyObject GetMyObjectById(int id)
         {
            return dao.GetMyObjectById(id);
         }
    }
    

    另一种计划可能是考虑使用RESTFUL 服务。

    【讨论】:

    • 不确定你的意思。我正在使用两个接口。一个描述 dao 对象,另一个继承它以便通过 wcf 公开 dao 功能。它基本上是一种强制 wcf 将所有 dao 方法公开为操作合同的方法。
    猜你喜欢
    • 2012-05-12
    • 2010-12-13
    • 2010-10-22
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 2010-09-06
    • 2021-12-29
    • 2022-01-15
    相关资源
    最近更新 更多