How to get a link to a WCF service object from the code that creates it?

I am modifying the code in this tutorial to create the push client / subscription base classes of the push push server, and I just hit a little brick wall.

The server class in the tutorial is created using the following code:

class Program
  {
    static void Main(string[] args)
    {
      using (ServiceHost host = new ServiceHost(
        typeof(StringReverser),
        new Uri[]{
          new Uri("net.pipe://localhost")
        }))
      {

        host.AddServiceEndpoint(typeof(IStringReverser),
          new NetNamedPipeBinding(),
          "PipeReverse");

        host.Open();

        Console.WriteLine("Service is available. " +
          "Press <ENTER> to exit.");
        Console.ReadLine();

        host.Close();
      }
    }
  }

I assume I posted an instance of StringReverser . My problem is that I need a link to this instance, so I can call the method on it to return data to the client.

In the tutorial, the server simply responds to the client using the callback method, instead I save the link to the client in the list of subscribers. When I need to send data back to clients, I need a reference to a service object, so I really can use a callback.

WCF, ? ?

...

+3
3

singleton StringReverser ServiceHost:

ServiceHost host = new ServiceHost(
  StringReverser.Instance,
  new Uri[]{new Uri("net.pipe://localhost")}
);
+2

, - , ( , .NET 4.5). , , ServiceHost Single. , ServiceHost Open().

. , SO:

var baseAddress = new Uri("http://localhost:15003/MockGateway");

using (var host = new ServiceHost(new MockGatewayService(), baseAddress))
{
    // Since we are passing an instance of the service into ServiceHost (rather 
    // than passing in the type) we have to set the context mode to single.
    var behavior = host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
    behavior.InstanceContextMode = InstanceContextMode.Single;

    // Continue to use the service here.  If you ever need to get a reference
    // to the service object you can do so with...
    MockGatewayService myService = host.SingletonInstance as MockGatewayService;

    // ...
}
+2

servicecontract

OperationContext.Current.GetCallbackChannel());

, , , . , . , . / , (), , WCF (). , , , IInstanceProvider IEndPointBehavior, , . , . , , , . , , , , .

0
source

Source: https://habr.com/ru/post/1703820/


All Articles