Search code examples
c#wcff#routeswcf-routing

WCF 4.0 routing with mex using System.ServiceModel.Routing.RoutingService


I have service with working MEX at:

net.tcp://remotehost:4508

What is the shortest C#/F# code (hard time understanding XML configuration files ^_^") I could write to create a router to it at?:

net.tcp://localhost:4508

MEX should also be routed properly so that clients can use the router

svcutil net.tcp://localhost:4508

to discover service methods.


Solution

  • Here's my answer to my question that does exactly what I want - without any XML salad, in less then 50 lines of F#:

    namespace CORSIS
    
    module Application =
    
        open System
    
        open System.ServiceModel
        open System.ServiceModel.Routing
        open System.ServiceModel.Dispatcher
        open System.ServiceModel.Description
    
    
        let createSimpleRouter createBinding (routerAddress : string) serviceAddress = 
    
            let routerType = typeof<IRequestReplyRouter>
            let routerContract = ContractDescription.GetContract(routerType)
            let endpoint address = new ServiceEndpoint(routerContract, createBinding(), new EndpointAddress(address))
    
            let serviceEndpoints = [| endpoint serviceAddress |]
            let configuration = new RoutingConfiguration()
            configuration.FilterTable.Add(new MatchAllMessageFilter(), serviceEndpoints)
    
            let host = new ServiceHost(typeof<RoutingService>)
            ignore <| host.AddServiceEndpoint(routerType, createBinding(), routerAddress)
            host.Description.Behaviors.Add(new RoutingBehavior(configuration))
            host        
    
        [<EntryPoint>]
        let main(args) =
    
            let (routerAddress, serviceAddress) =
                match args with
                | [| ra; sa |] -> (ra, sa)
                | _ -> ("net.tcp://localhost:4508/", "net.tcp://remotehost:4508/")
    
            let netTcp() = new NetTcpBinding(SecurityMode.None)
            let mexTcp() = MetadataExchangeBindings.CreateMexTcpBinding()
    
            let tcpRouter = createSimpleRouter netTcp  routerAddress           serviceAddress
            let mexRouter = createSimpleRouter mexTcp (routerAddress + "mex") (serviceAddress + "mex")
    
            tcpRouter.Open()
            mexRouter.Open()
    
            Console.WriteLine("routing ...\n{0} <-> R:{1}", serviceAddress, routerAddress)
    
            ignore <| Console.ReadKey true
    
            0