2014-01-09 86 views
0

我有一些api控制器,我想在運行時在我的mvc應用程序中註冊。 控制器本身駐留到類庫項目,看起來像:在運行時註冊自定義控制器

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

我已經編譯庫(給它取名爲Injection.dll),並在我的MVC應用程序嘗試註冊通過Unity.Mvc庫容器那些控制器

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)); 
    } 
} 

如此看來,登記工作正常,我沒有錯誤,同時debuggig,但 我沒有期望的結果,當我瀏覽到API /自定義/獲取本人曾經The resource cannot be found.錯誤瀏覽器。 請幫助我想念這裏。

+0

你有沒有配置1路線爲web api? 2.統一控制器工廠爲您的附加自定義API控制器? –

回答

2

MVC和Web API都有自己的依賴關係解析器。

您的代碼註冊MVC Dependeny解析器:

DependencyResolver.SetResolver(yourResolver); 

您需要註冊什麼是Web API依賴解析器,像這樣:

GlobalConfiguration.Configuration.DependencyResolver = yourResolver; 

在這兩種情況下的預期解析器必須實現IDependencyResolver,但它服務於不同的目的。

不建議您爲這兩件事共享相同的依賴關係解析器(因此容器和組合根)。如果您需要這樣做,請使用兩個不同的IDependencyResolver實例並在其所屬的位置註冊控制器。

重要提示 有兩種不同的IDependencyResolver接口,一個用於MVC和其他的Web API。它們具有相同的名稱,但名稱空間不同。而你需要實現適合於各種情況下(或兩者兼而有之,如果你需要實現DI兩個MVC和Web API):