c# - 服务类可以以及如何继承普通类?

标签 c# wcf inheritance service

我有两个服务 TestService1 和 TestService2。我可以从没有 ServiceBehaviorAttribute 属性的普通类继承这两种服务吗?像这样:

public class ServiceBase
{
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class TestService1 : ServiceBase, ITestService1
{
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class TestService2 : ServiceBase, ITestService2
{
}

ServiceBehaviorAttribute 属性的行为是否会应用于继承普通类的继承成员?

我是否需要向基础普通类添加一些特定于服务的属性?

如果我的实现有误,如何正确实现这样的继承——服务从另一个普通类继承一些行为?

更新。 这与 ServiceBehaviorAttribute attribute inheritance 无关.我问更常见的问题——我可以从 WCF 服务类中的另一个类(例如,在外部 DLL 中,甚至不与 WCF 关联)继承一些功能吗?如何?我的代码是否有效并且没有隐藏的细微差别?

最佳答案

[ServiceBehavior] 可以应用于基类,这样派生的服务类将继承该行为。

改变这个:

public class ServiceBase
{
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class TestService1 : ServiceBase, ITestService1
{
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class TestService2 : ServiceBase, ITestService2
{
}

...为此:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class ServiceBase
{
}

public class TestService1 : ServiceBase, ITestService1
{
}

public class TestService2 : ServiceBase, ITestService2
{
}

can I inherit some functionality from another class (that is in outside DLL for example, that doesn't even associated with WCF) in WCF service class?

当然,ServiceBase 可以有 TestService1TestService2 可以使用的方法。但是,WCF 客户端只会看到在您的接口(interface) ITestService1ITestService2 上定义的方法,即使 ServiceBase.SomeMethod() 是公开的也是如此。

例如

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class ServiceBase
{
    // TestService1 and TestService2  may call me 
    // but not WCF clients. I'm invisible
    public void SomeMethod () {}
}

public class TestService1 : ServiceBase, ITestService1
{
    public void SomeServiceMethod1() { SomeMethod(); }
}

public class TestService2 : ServiceBase, ITestService2
{
    public void SomeServiceMethod2() { SomeMethod(); }
}

关于基类与 WCF 无关的更新,“是的,你可以”。这与调用任何其他基类没有什么不同。

关于c# - 服务类可以以及如何继承普通类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35308107/

相关文章:

c# - 查看有很多组件。多个模型对象?

c# - 摆脱不安全的代码,从字节编码 uint 数组?

wcf - 如何让IIS等待WCF服务准备好?

wcf - Web 服务响应 XML 检索 'DestinationUnreachable' 消息

c# - 设置 HttpContext.Current.User 抛出空引用异常

javascript - 理解 typescript 继承

c# - 如何在 C# WinForms 按钮中左右对齐文本?

c# - 没有年份值的 Datetime.tryparse

javascript - react : reach the component's parent or transfer data from parent to child

java - 扩展类不能继承方法吗?