GeminiYellow
GeminiYellow

Reputation: 1013

[WCF]two service in the same process

i have one exe. in this exe. i start a service, call it serviceManager and then, start another service, call it serviceChild.

when i use serviceChild create a channel with serviceManager, call the serviceManager's callback. it will freez.

all the service binding is netnamedpipebinding.

who can tell me what is happend?

and my code: interface:

[ServiceContract]
internal interface IChild
{
    [OperationContract]
    CommunicationState GetState();
}

[ServiceContract]
public interface IManager
{
    [OperationContract]
    CommunicationState GetState();
}

and:

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant, InstanceContextMode = InstanceContextMode.Single)]
public class Child : IChild
{
    private readonly Guid _address = Guid.NewGuid();
    private readonly ServiceHost _host;

    public Guid Address
    {
        get { return _address; }
    }

    public Child()
    {
        _host = new ServiceHost(this);

        var binding = new NetNamedPipeBinding();
        var clientAddress = Helper.GetClientAddress(_address);
        _host.AddServiceEndpoint((typeof(IChild)), binding, clientAddress);

        _host.Description.Behaviors.Add(new ServiceDiscoveryBehavior());
        _host.AddServiceEndpoint(new UdpDiscoveryEndpoint());

        _host.Open();
    }

    public void Open()
    {
        if(!Manager.IsRunning()){Manager.Start();}

        var binding = new NetNamedPipeBinding();
        var endpoint = new EndpointAddress(Constants.ADDRESS_PIPE_SERVER);
        using (var factory = new ChannelFactory<IManager>(binding, endpoint))
        {
            IManager managerChannel = null;
            try
            {
                managerChannel = factory.CreateChannel();
                **managerChannel.GetState();**// BUG:<-----
            }
            catch (Exception ex)
            {
                MessageBox.Show("ex " + ex);
            }
            finally
            {
                Helper.CloseChannel((ICommunicationObject)managerChannel);
            }
        }
    }

    public CommunicationState GetState()
    {
        return _host.State;
    }
}

the manager:

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant, InstanceContextMode = InstanceContextMode.Single)]
public class Manager : IManager
{
    private static ServiceHost _host;

    private static Manager _instance;

    private static Manager Instance
    {
        get { return _instance ?? (_instance = new Manager()); }
    }

    #region IManager Members

    public CommunicationState GetState()
    {
        return _host.State;
    }

    #endregion

    public static void Start()
    {
        if (_host != null
            && (_host.State == CommunicationState.Created
                || _host.State == CommunicationState.Opening
                || _host.State == CommunicationState.Opened))
        {
            return;
        }


        _host = new ServiceHost(Instance);

        var binding = new NetNamedPipeBinding();
        var endpoint = Constants.ADDRESS_PIPE_SERVER;
        _host.AddServiceEndpoint((typeof (IManager)), binding, endpoint);
        _host.Open();
    }

    public static bool IsRunning()
    {
        var binding = new NetNamedPipeBinding();
        var endpointAddress = new EndpointAddress(Constants.ADDRESS_PIPE_SERVER);
        var factory = new ChannelFactory<IManager>(binding, endpointAddress);
        IManager managerChannel = null;
        try
        {
            managerChannel = factory.CreateChannel();
            // wait for server to respond
            if (_host != null && _host.State == CommunicationState.Opened)
            {
                var contextChannel = managerChannel as IClientChannel;
                if (contextChannel != null) contextChannel.OperationTimeout = TimeSpan.FromMilliseconds(1000);
            }
            try
            {
                managerChannel.GetState();
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }
        catch (EndpointNotFoundException e)
        {
            return false;
        }
        finally
        {
            Helper.CloseChannel((ICommunicationObject) managerChannel);
        }
    }

others:

internal static class Helper
{
    public static void CloseChannel(ICommunicationObject channel)
    {
        try
        {
            if (channel.State == CommunicationState.Opened) channel.Close();
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }
        finally
        {
            channel.Abort();
        }
    }

    public static string GetClientAddress(object serviceAddress)
    {
        return string.Format(Constants.ADDRESS_PIPE_CLIENT_FORMAT, serviceAddress);
    }
}


internal static class Constants
{
    internal static string ADDRESS_PIPE_SERVER = @"net.pipe://localhost/Server";
    internal static string ADDRESS_PIPE_CLIENT_FORMAT = @"net.pipe://localhost/Client_{0}";
}

at last , the test:

private void ActionLoaded(object sender, RoutedEventArgs e)
    {
        Manager.Start();
    }

    private void ActionConnectedSelf(object sender, RoutedEventArgs e)
    {
        var client = new Child();
        client.Open();
    }

Upvotes: 1

Views: 895

Answers (1)

marc_s
marc_s

Reputation: 755157

I like to structure my WCF solutions like this:

Contracts (class library)
Contains all the service, operations, fault, and data contracts. Can be shared between server and client in a pure .NET-to-.NET scenario

Service implementation (class library)
Contains the code to implement the services, and any support/helper methods needed to achieve this. Nothing else.

Service host(s) (optional - can be Winforms, Console App, NT Service)
Contains service host(s) for debugging/testing, or possibly also for production.

This basically gives me the server-side of things.

On the client side:

Client proxies (class library)
I like to package my client proxies into a separate class library, so that they can be reused by multiple actual client apps. This can be done using svcutil or "Add Service Reference" and manually tweaking the resulting horrible app.config's, or by doing manual implementation of client proxies (when sharing the contracts assembly) using ClientBase<T> or ChannelFactory<T> constructs.

1-n actual clients (any type of app)
Will typically only reference the client proxies assembly, or maybe the contracts assembly, too, if it's being shared. This can be ASP.NET, WPF, Winforms, console app, other services - you name it.

That way; I have a nice and clean layout, I use it consistently over and over again, and I really think this has made my code cleaner and easier to maintain.

This was inspired by Miguel Castro's Extreme WCF screen cast on DotNet Rocks TV with Carl Franklin - highly recommended screen cast !

Upvotes: 4

Related Questions