RobinJiangdh
6/6/2017 - 3:37 PM

ASP.NET Web API: Controlling assemblies loaded by providing own AssembliesResolver

ASP.NET Web API: Controlling assemblies loaded by providing own AssembliesResolver

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Dispatcher;
using System.Web.Http.SelfHost;

namespace SelfHost
{
    class Program
    {
        static HttpSelfHostServer CreateHost(string address)
        {
            // Create normal config
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address);

            // Set our own assembly resolver where we add the assemblies we need
            AssembliesResolver assemblyResolver = new AssembliesResolver();
            config.Services.Replace(typeof(IAssembliesResolver), assemblyResolver);

            // Add a route
            config.Routes.MapHttpRoute(
              name: "default",
              routeTemplate: "api/{controller}/{id}",
              defaults: new { controller = "Home", id = RouteParameter.Optional });

            HttpSelfHostServer server = new HttpSelfHostServer(config);
            server.OpenAsync().Wait();

            Console.WriteLine("Listening on " + address);
            return server;
        }

        static void Main(string[] args)
        {
            // Create and open our host
            HttpSelfHostServer server = CreateHost("http://localhost:8080");

            Console.WriteLine("Hit ENTER to exit...");
            Console.ReadLine();
        }
    }

    class AssembliesResolver : DefaultAssembliesResolver
    {
        public override ICollection<Assembly> GetAssemblies()
        {
            ICollection<Assembly> baseAssemblies = base.GetAssemblies();
            List<Assembly> assemblies = new List<Assembly>(baseAssemblies);

            // Add whatever additional assemblies you wish

            return assemblies;
        }
    }
}