Reputation: 829
I have a WCF service implementing a service contract with only one method 'foo'.
[ServiceContract]
public interface IWCFService
{
[OperationContract]
void Foo(MyEntity entity);
}
I'm implementing this interface with some added properties and an event.
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);
}
}
}
On another class in the same server application, I'm suscribing to '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...
}
}
The problem is that, even though I've checked with the debugger that the function FunctionThatDoesSomethingWithMyEntity has successfully suscribed to MyEvent in OtherClass.Start(), when the client calls the WCF service method Foo, MyEvent is null.
Furthermore, I noticed the following error while stopping at a breakpoint inside Foo:
error CS1061: 'MyWCFService' does not contain a definition for 'MyWCF' and no extension method 'MyWCF' accepting a first argument of type 'MyWCFService' could be found (are you missing a using directive or an assembly reference?)
I believe that each time the clients call Foo a new MyWCFService object is created and therefore MyEvent is null, is there an explanation for this?
Upvotes: 0
Views: 171
Reputation: 3551
Events don't work across WCF like you are expecting them to do.This question, might help you out though. Basically you need to use callbacks instead.
Edit: Since you clarified and are trying to bind to the event not over WCF, but in another class on the server/WCF project, you are correct in your assumption that each instance of the WCF client created spawns a new class and therefore loses the event binding. I can't promise it would work as I can't test it at the moment, but you could try making the event "static" so it wouldn't get created with each new class instance.
Upvotes: 1