Self-hosting WebAPI application referencing controller from different assembly

我与影子孤独终老i 提交于 2019-11-30 12:41:31
cypressx

This seems to be a known issue. You have to force the .NET to load the assemblies with the Controllers you need.

Before you Self Host the Web API, you should retrieve a type from the Reference Assembly which you want to be loaded by the runtime. Something like this:

Type controllerType = typeof(ReferencedControllers.ControllerType);

This should load the controllers from this assembly and it won't give you 404 error.

Previous posts of Praveen and Janushirsha lead me into the right direction I resume here :

// Not reliable in Release mode :
Type controllerType = typeof(ReferencedControllers.ControllerType);

So, you should replace IAssembliesResolver with :

HttpConfiguration config = new HttpConfiguration();
config.Services.Replace(typeof(IAssembliesResolver), new CustomAssembliesResolver());

Here is an example of implementation for CustomAssembliesResolver

using System.Web.Http.Dispatcher;
internal class CustomAssembliesResolver : DefaultAssembliesResolver
{
    public override ICollection<System.Reflection.Assembly> GetAssemblies()
    {
        var assemblies = base.GetAssemblies();

        // Interestingly, if we push the same assembly twice in the collection,
        // an InvalidOperationException suggests that there is different 
        // controllers of the same name (I think it's a bug of WebApi 2.1).
        var customControllersAssembly = typeof(AnotherReferencedAssembly.MyValuesController).Assembly;
        if (!assemblies.Contains(customControllersAssembly))
            assemblies.Add(customControllersAssembly);

        return assemblies;
    }
}

This code can easily be adapted if third party assemblies are not referenced or if you want late assembly binding.

Hope this help.

this link saved my day for the same problem :)...

I just need to change below statement to suit for the selfhost webapi configuration.

GlobalConfiguration.Configuration.Services.Replace(typeof(IAssembliesResolver), new CustomAssemblyResolver());

with

var config = new HttpSelfHostConfiguration("http://localhost:8081");
        config.Services.Replace(typeof(IAssembliesResolver), new CustomAssemblyResolver());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!