【问题标题】:WCF net tcp service object has null eventWCF net tcp 服务对象有空事件
【发布时间】:2015-12-10 17:53:36
【问题描述】:

我有一个 WCF 服务实现了一个只有一个方法“foo”的服务合同。

[ServiceContract]
public interface IWCFService
{
    [OperationContract]
    void Foo(MyEntity entity);
}

我正在使用一些添加的属性和一个事件来实现这个接口。

internal class MyWCFService : IWCFService
{
    public event EventHandler MyEvent;

    public string Name { get; set; }

    private ServiceHost WCFServiceHost { get; set; }

    internal MyWCFService()
    {
        NetTcpBinding tcpBinding = new NetTcpBinding();
        tcpBinding.Security.Mode = SecurityMode.None;

        WCFServiceHost = new ServiceHost(typeof(MyWCFService), new Uri[] { new Uri("net.tcp://xxx.xxx.xxx.xxx:61243") });

        WCFServiceHost.AddServiceEndpoint(typeof(IWCFService), tcpBinding, "MyWCFService");
    }

    internal void Start()
    {
        WCFServiceHost.Open();            
    }

    internal void Stop()
    {
        this.WCFServiceHost.Close(new TimeSpan(0, 0, 1));
    }

    void IWCFService.Foo(MyEntity entity)
    {
        //Business logic...

        ThrowEvent(entity);
    }

    private void ThrowEvent(MyEntity entity)
    {
        if (this.MyEvent != null) //this.MyEvent is always null even though I'd successfully suscribe a function in another class
        {
            this.MyEvent(entity);
        }
    }
}

在另一个类在同一服务器应用程序中,我订阅了“MyEvent”。

public class AnotherClass
{
    internal MyWCFService TheService { get; set; } = new MyWCFService();

    public void Start()
    {
        this.TheService.MyEvent += FunctionThatDoesSomethingWithMyEntity;
        //Breakpoint here, this.TheService.MyEvent has 1 suscriber
        this.TheService.Start();
    }

    private void FunctionThatDoesSomethingWithMyEntity(MyEntity entity)
    {
         //More logic...
    }
}

问题是,即使我已经用调试器检查了函数 FunctionThatDoesSomethingWithMyEntity 已成功订阅 OtherClass.Start()MyEvent /em>,当客户端调用WCF服务方法Foo时,MyEvent为null。

此外,在 Foo 内的断点处停止时,我注意到以下错误:
错误 CS1061:“MyWCFService”不包含“MyWCF”的定义,并且没有扩展方法“MyWCF”接受第一个参数可以找到“MyWCFService”类型的(您是否缺少 using 指令或程序集引用?)

我相信每次客户调用 Foo 时都会创建一个新的 MyWCFService 对象,因此 MyEvent 为空,有对此的解释吗?

【问题讨论】:

    标签: c# .net wcf events nettcpbinding


    【解决方案1】:

    事件不会像您期望的那样在 WCF 中起作用。This question,不过可能会对您有所帮助。基本上你需要使用回调来代替。

    编辑:由于您澄清并尝试绑定到事件,而不是通过 WCF,而是在服务器/WCF 项目的另一个类中,您的假设是正确的,即创建的 WCF 客户端的每个实例都会产生一个新类和因此失去事件绑定。我不能保证它会起作用,因为我目前无法对其进行测试,但您可以尝试将事件设置为“静态”,这样它就不会在每个新类实例中创建。

    【讨论】:

    • 我忘了说,这个事件不是给客户端的,AnotherClass是托管在服务器上的。
    • 编辑希望能帮助你。
    • 好的,让我试试,我会回来的。
    猜你喜欢
    • 1970-01-01
    • 2012-02-15
    • 2011-08-09
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    相关资源
    最近更新 更多