Archive for the ‘Web Services’ Category


You are currently browsing the archives for the Web Services category.

Archives

  • Categories

  • Integrating StructureMap with WCF 4.0 REST Services

    Monday, August 16th, 2010

    Ok first things first this post borrows a lot of code from  Jimmy Bogard’s post from a couple of years ago entitled Integrating StructureMap With WCF so credit where credits due. However there are a couple of minor changes that you need to make in order to get StructureMap to work properly with your WCF RESTful service.

     

    Create A Custom Instance Provider

    This code is identical to Jimmy’s original code.

    public class StructureMapInstanceProvider : IInstanceProvider

    {

        private readonly Type _serviceType;

     

        public StructureMapInstanceProvider(Type serviceType)

        {

            _serviceType = serviceType;

        }

     

        #region IInstanceProvider Members

     

        public object GetInstance(InstanceContext instanceContext)

        {

            return GetInstance(instanceContext, null);

        }

     

        public object GetInstance(InstanceContext instanceContext, Message message)

        {

            return ObjectFactory.GetInstance(_serviceType);

        }

     

        public void ReleaseInstance(InstanceContext instanceContext, object instance)

        {

        }

     

        #endregion

    }

     

    Create A Custom Service Behaviour Class

    This code is identical to Jimmy’s original code.

    public class StructureMapServiceBehaviour : IServiceBehavior

       {

           #region IServiceBehavior Members

     

           public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)

           {

               foreach (var endpointDispatcher in

                   serviceHostBase.ChannelDispatchers.OfType<ChannelDispatcher>().SelectMany(

                       channelDispatcher => channelDispatcher.Endpoints))

               {

                   endpointDispatcher.DispatchRuntime.InstanceProvider =

                       new StructureMapInstanceProvider(serviceDescription.ServiceType);

               }

           }

     

           public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase,

                                            Collection<ServiceEndpoint> endpoints,

                                            BindingParameterCollection bindingParameters)

           {

           }

     

           public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)

           {

           }

     

           #endregion

       }

     

    Create A Custom Service Host

    This code is almost identical to Jimmy’s. The only difference is that your custom class should inherit from the WebServiceHost class rather than the normal ServiceHost class for normal WCF Services.

    public class StructureMapWebServiceHost : WebServiceHost

    {

        public StructureMapWebServiceHost()

        {

        }

     

        public StructureMapWebServiceHost(object singletonInstance, params Uri[] baseAddresses) : base(singletonInstance, baseAddresses)

        {

        }

     

        public StructureMapWebServiceHost(Type serviceType, params Uri[] baseAddresses) : base(serviceType, baseAddresses)

        {

        }

     

        protected override void OnOpening()

        {

            Description.Behaviors.Add(new StructureMapServiceBehaviour());

            base.OnOpening();

        }

    }

     

    Create A Custom Service Host Factory

    Once again this code is almost identical to Jimmy’s. The only difference is that we inherit from WebServiceHostFactory rather than the usual ServiceHostFactory class.

    /// <summary>

    /// StructureMap Service Host Factory for WCF REST Services

    /// </summary>

    public class StructureMapWebServiceHostFactory : WebServiceHostFactory

    {

        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)

        {

            return new StructureMapWebServiceHost(serviceType, baseAddresses);

        }

    }

     

    Wiring Up Our Route

    In our Global.asax file create our route using the StructureMapWebServiceHostFactory rather than the normal WebServiceHostFactory.

    public class Global : HttpApplication

    {

        void Application_Start(object sender, EventArgs e)

        {

            IoC.RegisterDependencies();

     

            RegisterRoutes();

        }

     

        private void RegisterRoutes()

        {       

            RouteTable.Routes.Add(new ServiceRoute("ReferenceData", new StructureMapWebServiceHostFactory(), typeof(ReferenceData)));

        }

    }

    Command Line Script for Calling REST Based Web Services

    Tuesday, July 13th, 2010

    I have been working with REST based web services recently and whilst reading the very useful and interesting article A Guide to Designing and Building RESTful Web Services with WCF 3.5 hosted on the Microsoft web site. Came across this useful little JavaScript script that can be called from the command line to invoke your  RESTful web services.

    The code is shown below.

    if (WScript.Arguments.length < 2)

    {

       WScript.echo("Client HTTP Request Utility\n");

       WScript.echo("usage: httprequest method uri [options]");

       WScript.echo("  -f filename");

       WScript.echo("  -h headerName headerValue");

       WScript.Quit(1);

    }

    var method = WScript.Arguments.Item(0);

    var uri = WScript.Arguments.Item(1);

    var req = new ActiveXObject("MSXML2.XMLHTTP");

    var filename = null;

    req.Open(method, uri, false);

    
    

    WScript.echo("********* Request ********* ");

    WScript.echo(method + " " + uri + " HTTP/1.1");

    for (i=2; i < WScript.Arguments.length; i++)

    {

        var option = WScript.Arguments.Item(i);

        if (option == "-f")

            filename = WScript.Arguments.Item(i+1);

        if (option == "-h")

        {

            WScript.echo(WScript.Arguments.Item(i+1) + ": " +

                WScript.Arguments.Item(i+2));

            req.setRequestHeader(WScript.Arguments.Item(i+1),

                WScript.Arguments.Item(i+2));

        }

    }

    try

    {

           if (filename != null)

           {

    
    

              var fso = new ActiveXObject("Scripting.FileSystemObject");

              var file = fso.OpenTextFile(filename, 1, false);

              var fileContents = file.ReadAll();

              file.Close();

              WScript.echo(fileContents);

              req.Send(fileContents);

              printResponse(req);

           }

           else

           {

              req.send();

              printResponse(req);

           }

    }

    catch(e)

    {

    
    

       WScript.echo("******* Response ********* ");

       WScript.echo(e.message);

    }

    function printResponse(req)

    {

    
    

       WScript.echo("******* Response ********* ");

       WScript.echo("HTTP/1.1" + " " + req.status + " " + req.statusText);

       var headers = req.getAllResponseHeaders();

       WScript.echo(headers);

       WScript.echo(req.responseText);

    }

    To perform a GET simply type from the command line:

    HttpUtility.js get http://localhost:1189/Service.svc/

    where HttpUtility.js is the file name containing the JavaScript code shown above and the URL of our REST service.

    To perform a POST:

    HttpUtility.js post http://localhost:1189/Service.svc/ –f message.xml -h Content-Type application/xml

    where the –f argument specifies the filename with the message contents and the –h argument indicates the header name and header value.

    The source code can be downloaded from here.