Click here to Skip to main content
15,896,154 members
Articles / General Programming

Self Hosted Web API Wrapper Class

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
5 Sep 2013CPOL2 min read 11.5K   153   5  
A wrapper class to simplify the implementation of a Self Hosted Web API Service
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Dispatcher;
using System.Web.Http.SelfHost;
using System.Web.Http;

namespace WebAPI_Host
{
    public class WebAPI_Host
    {
        #region Private Variables
        private AssembliesResolver _AssembliesResolver = new AssembliesResolver();
        private HttpSelfHostConfiguration _WebHostConfig = null;
        private HttpSelfHostServer _Server = null;
        #endregion

        #region Constructor
        /// <summary>
        /// Class Constructor
        /// </summary>
        /// <param name="BaseAdress">The base address with which to configure the Web API Host.</param>
        public WebAPI_Host(string BaseAddress)
        {
            _WebHostConfig = new HttpSelfHostConfiguration(BaseAddress.Trim());
        }

        /// <summary>
        /// Default constructor (Base Address = http://localhost:8080)
        /// </summary>
        public WebAPI_Host()
        {
            _WebHostConfig = new HttpSelfHostConfiguration("http://localhost:8080");
        }
        #endregion

        #region Public Functionss
        /// <summary>
        /// Add a DLL File containing the Controllers to be hosted.
        /// </summary>
        /// <param name="FileName">A fully qualified pat to the DLL File.</param>
        public void AddLibrary(string FileName)
        {
            _AssembliesResolver.AddLibraryFile(FileName);
        }

        /// <summary>
        /// Function allows for the setting up of a route for the WebAPI Host.
        /// </summary>
        /// <param name="RouteName"></param>
        /// <param name="RouteTemplate"></param>
        /// <param name="Defaults"></param>
        public void AddRoute(string RouteName,
                             string RouteTemplate,
                             object Defaults)
        {
            _WebHostConfig.Routes.MapHttpRoute(RouteName,
                                               RouteTemplate,
                                               Defaults);                                                
        }

        /// <summary>
        /// Start the Web API Service.
        /// </summary>
        public void StartWebAPIHost()
        {
            _WebHostConfig.Services.Replace(typeof(IAssembliesResolver), _AssembliesResolver);

            _Server = new HttpSelfHostServer(_WebHostConfig);
            _Server.OpenAsync().Wait();
        }

        /// <summary>
        /// Stop the Service Listener.
        /// </summary>
        public void StopWebAPIHost()
        {
            _Server.CloseAsync();
        }
        #endregion
    }

    class AssembliesResolver : DefaultAssembliesResolver
    {
        private List<string> _LibraryFileList = new List<string>();

        /// <summary>
        /// Function will add a file to the library list.
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public void AddLibraryFile(string FileName)
        {
            // Make sure the file is not already on the List
            if (_LibraryFileList.Contains(FileName.ToUpper().Trim()))
            {
                throw new Exception("File already on the WEB Api Library List.");
            }

            // Make sure that the file actually exists.
            if (!File.Exists(FileName.Trim()))
            {
                throw new Exception("Specified WEB Api Library file does not exist!");
            }

            _LibraryFileList.Add(FileName.ToUpper().Trim());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override ICollection<Assembly> GetAssemblies()
        {
            ICollection<Assembly> baseAssemblies = base.GetAssemblies();
            List<Assembly> assemblies = new List<Assembly>(baseAssemblies);

            //assemblies.Add(Assembly.LoadFrom(@"C:\Users\david.kolosowski\Documents\Visual Studio 2010\Projects\WebAPISelfHost\WebAPISelfHost\bin\Debug\ClassLibrary1.dll"));
            foreach (string sFile in _LibraryFileList)
            {
                assemblies.Add(Assembly.LoadFrom(sFile));
            }

            return assemblies;
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
South Africa South Africa
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions