Created
May 9, 2014 07:43
-
-
Save ionoy/a67606e5b6bbbefafebf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Reflection; | |
using System.ServiceModel; | |
using LinFu.DynamicProxy; | |
namespace UAV.Communication | |
{ | |
public static class CommunicationHelpers | |
{ | |
private static T GetProxy<T>() where T : new() | |
{ | |
var type = typeof (T); | |
if(type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance).Any(m => !m.IsVirtual || m.IsFinal)) | |
throw new InvalidOperationException("All public methods of type " + type.Name + " should be virtual."); | |
var proxyFactory = new ProxyFactory(); | |
var uavControl = new T(); | |
var loggingInterceptor = new LoggingInterceptor(uavControl); | |
return proxyFactory.CreateProxy<T>(loggingInterceptor); | |
} | |
public static ServiceHost CreateHost<T>(string hostSuffix = "") where T : new() | |
{ | |
var proxy = GetProxy<T>(); | |
var host = new ServiceHost(proxy, new[] {new Uri("net.pipe://localhost")}); | |
host.Description.Behaviors.Find<ServiceBehaviorAttribute>().InstanceContextMode = InstanceContextMode.Single; | |
host.AddServiceEndpoint(typeof(IUAVControl), new NetNamedPipeBinding(), "UavPipe" + hostSuffix); | |
return host; | |
} | |
public static IUAVControl CreateClient(string hostSuffix = "") | |
{ | |
var pipeFactory = new ChannelFactory<IUAVControl>(new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/UavPipe" + hostSuffix)); | |
var uavControl = pipeFactory.CreateChannel(); | |
((IClientChannel)uavControl).Open(); | |
return uavControl; | |
} | |
public static void Disconnect(IUAVControl uavControl) | |
{ | |
((IClientChannel)uavControl).Abort(); | |
((IClientChannel)uavControl).Close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment