Register custom controller in runtime

北城以北 提交于 2019-12-25 03:05:56

问题


I've some api controller that i want to register at runtime in my mvc application. The controller itself resides into Class Library project and looks like:

public class CustomController : ApiController
{
    public string Get()
    {
        return "Hello";
    }       
}

I've compile that library (gave it a name Injection.dll), and in my mvc app try to register those controller via Unity.Mvc library container

public static class UnityConfig
{
    public static void RegisterComponents()
    {
        var container = new UnityContainer();

        // register all your components with the container here
        // it is NOT necessary to register your controllers

        // e.g. container.RegisterType<ITestService, TestService>();

        Assembly customLogicAssembly = Assembly.LoadFrom(HttpContext.Current.Server.MapPath("~/bin/" + "Injection.dll"));
        Type existingType = customLogicAssembly.GetTypes().First();
        container.RegisterType(existingType);

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }
}

So it seems that registration works fine and i have no errors while debuggig it, but i don't have expected result, when i navigate to api/Custom/Get i have an The resource cannot be found. error in browser. Pls help what i miss here.


回答1:


MVC and Web API have each its own dependency resolver.

Your code is registering the MVC Dependeny Resolver:

DependencyResolver.SetResolver(yourResolver);

What you need to register is the Web API Dependency resolver, like this:

GlobalConfiguration.Configuration.DependencyResolver = yourResolver;

The expected resolver in both cases must implement IDependencyResolver, but it serves a different purpose.

It's not recommended that you share the same dependency resolver (thus container and composition root) for both things. If you need to do so, use two different instances of IDependencyResolver and register the controllers where they belong.

IMPORTANT NOTE There are two different IDependencyResolver interfaces, one for MVC, and the other for Web API. They have the same name, but are on different namespaces. And you need to implement the appropriate for each case (or both, if you need to implement DI for both MVC and Web API):

  • System.Web.Mvc.IDependencyResolver, for MVC
  • System.Web.Http.Dependencies.IDependencyResolver, for Web API


来源:https://stackoverflow.com/questions/21021986/register-custom-controller-in-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!