tags:

views:

231

answers:

2

Is it possible to retrieve the concrete class instance from the ServiceHost, so that I can add an event handler for the events of that class?

Public Class Widget
      Public Event MessageCalled(sender as object, e as EventArgs)
      Public Sub DoSomething()
         '-- do a whole lot of stuff --'
         RaiseEvent MessageCalled(Me, new EventArgs())
      End Sub
End Class


Private _host As New ServiceHost(GetType(Widget), New Uri() {New Uri("http://localhost:50000")})

So when the client calls the DoSomething() method, I can handle the MessageCalled() event on the host.

Most of what I've found talks about handling events on the client, but I'm not interested in this.

+1  A: 

I don't totally understand what it is you're trying to do, but I guess you want to get the service class instance from your service host?

Well, think about this: if you have a service host on a busy system, there's a good chance you could have several concurrent client requests being served at the same time. By default, in WCF, each client request gets its own instance of the service class, which again means, the WCF runtime might be spinning up multiple instances of "Widget" from your service host - which one of those n instances is it that you want?

There is typically no 1:1 relationship between the ServiceHost and its hosted service class.... or at least you can't rely on that being a 1:1 relationship. I am not aware of any way to get the single (or all of the multiple) service class instance(s) given a ServiceHost instance, sorry.

I guess you need to rethink your design a bit and find a way to solve this requirement in a different way. I don't think right now in WCF you could do what you're trying to do.

marc_s
Thanks. I think that I am going to refactor. The code is legacy code that used remoting and used a seperate library that is common between the host and client. The host 'listened' to the common object for events.I'll just keep the Interface in the common library, and move the implementation of that class out of the common library into the host code.
Jayden
+1  A: 

I think you'd be better off using the extensibility points provided by the WCF runtime rather than trying to use an event like this. To get started, check out the section of the SDK entitled Extending WCF.

If you provide some more details on exactly what you're trying to achieve we can probably provide some more concrete suggestions on what to do, but juding by your sample code it appears like you just want to be involved with every message that is exchanged with your service so you can log some information? If that's the case then you probably want to implement an IDispatchMessageInspector.

Drew Marsh
Thanks. It looks like I could do it like this, however, as mentioned above, the code I'm adapting is legacy code that previousy used remoting. I think in the long term I'll be better to refactor to fit WCF better.
Jayden