如何获得具有多个类的WCF服务?

时间:2019-01-15 10:05:04

标签: c# wcf interface multiple-inheritance servicecontract

我想要这样的东西

Service1.svc.cs

namespace MyService
{
    public class User : IUser
    {
        ExternalLibrary.User externalUser = new ExternalLibrary.User();

        public string GetName()
        {
            return externalUser.GetName();
        }

        public bool SetName(string name)
        {
            return externalUser.SetName(name);
        }
    }

    public class Device : IDevice
    {
        ExternalLibrary.Device externalDevice = new ExternalLibrary.Device();

        public string GetDeviceName()
        {
            return externalDevice.GetDeviceName();
        }

        public bool SetDeviceName(string name)
        {
            return externalDevice.SetDeviceName(name);
        }
    }
}

现在,我正在尝试找到一种在WCF接口上实现这些类的方法。我尝试了一下,这不起作用:

namespace MyService
{
    [ServiceContract]
    public interface IMyService : IUser, IDevices
    {
        // nothing here
    }

    public interface IUSer
    {
        string GetName();
        bool SetName(string name);
    }

    public interface IDevice
    {
        string GetDeviceName();
        bool SetDeviceName(string name);
    }
}

我尝试这种方式的原因是因为我有太多的外部类,并且我不想每次为了获取用户名而调用服务时都为其创建对象。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

如果您希望他们根据一份服务合同,我相信您可以做到

namespace MyService
{
    [ServiceContract]
    public interface IMyService : IUSer, IDevice
    {
        [OperationContract]
        string GetName();
        [OperationContract]
        bool SetName(string name);
        [OperationContract]
        string GetDeviceName();
        [OperationContract]
        bool SetDeviceName(string name);
    }

    public interface IUSer
    {
        string GetName();
        bool SetName(string name);
    }

    public interface IDevice
    {
        string GetDeviceName();
        bool SetDeviceName(string name);
    }
}

然后声明类MyService的两个部分版本,每个版本都实现相应的接口,例如

namespace MyService
{
    public partial class MyService : IUser
    {
        ExternalLibrary.User externalUser = new ExternalLibrary.User();

        public string GetName()
        {
            return externalUser.GetName();
        }

        public bool SetName(string name)
        {
            return externalUser.SetName(name);
        }
    }

    public partial class MyService : IDevice
    {
        ExternalLibrary.Device externalDevice = new ExternalLibrary.Device();

        public string GetDeviceName()
        {
            return externalDevice.GetDeviceName();
        }

        public bool SetDeviceName(string name)
        {
            return externalDevice.SetDeviceName(name);
        }
    }
}