1

我正在構建一個非常簡單的控制器集,我想注入依賴項。MVC Web API和用於依賴項注入的Unity

我的Web Api項目正在使用.net 4.5.1(vs2015),我正在使用Unity進行依賴注入(對於Unity來說真的很新)。

這是我做了什麼:

  1. 新建項目> ASP.Net網機應用>網絡API項目(無身份驗證)
  2. 工具> NuGet包管理器>管理的解決方案包... 搜索「Unity.MVC」並安裝軟件包。
  3. 我創建了以下接口和類:

    public interface IExample 
    { 
        void DoWork(); 
    } 
    
    public class ServiceA : IExample 
    { 
        public void DoWork() 
        { 
         Console.Write("A"); 
        } 
    } 
    
    public class ServiceB : IExample 
    { 
        public void DoWork() 
        { 
         Console.Write("B"); 
        } 
    } 
    

在我簡單的控制器,我實現了這一點:

public class HomeController : Controller 
    { 
     IExample instance; 

     public HomeController(IExample injected) 
     { 
      instance = injected; 
     } 

     public ActionResult Index() 
     { 
      ViewBag.Title = "Home Page"; 

      return View(); 
     } 
    } 

我從Unity有這兩個新增加的文件:

enter image description here

我下面的代碼添加到UnityConfig.cs:

public static void RegisterTypes(IUnityContainer container) 
    { 
     // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements. 
     // container.LoadConfiguration(); 

     // TODO: Register your types here 
     //container.RegisterType<IProductRepository, ProductRepository>(); 

     container.RegisterType<IExample, ServiceA>(); 
    } 

到目前爲止 - ALL GOOD!正如預期的那樣,我將DI帶入了視野。現在我想要做我的網頁API控制器一樣的,就像這樣:

運行 - 與此錯誤:

An error occurred when trying to create a controller of type 'ItemController'. Make sure that the controller has a parameterless public constructor.

我做了什麼錯?全部例外:

{ 
    "Message": "An error has occurred.", 
    "ExceptionMessage": "An error occurred when trying to create a controller of type 'ItemController'. Make sure that the controller has a parameterless public constructor.", 
    "ExceptionType": "System.InvalidOperationException", 
    "StackTrace": " at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()", 
    "InnerException": { 
     "Message": "An error has occurred.", 
     "ExceptionMessage": "Type 'WebApplication2.Controllers.ItemController' does not have a default constructor", 
     "ExceptionType": "System.ArgumentException", 
     "StackTrace": " at System.Linq.Expressions.Expression.New(Type type)\r\n at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)" 
    } 
} 

在此先感謝!

+1

出於某種原因,由匿名用戶的承諾,它不會顯示出來,除非批准更多的一個用戶你的編輯標記。 – haim770

+1

根據你的(還有提議)更新,你只安裝了'Unity.Mvc',它負責與MVC的'DependecyResolver'集成。對於WebApi,您必須安裝Unity.WebAPI包:https://www.nuget.org/packages/Unity.WebAPI – haim770

+1

顯示您的'WebApiConfig.cs'和'UnityMvcActivator.cs'以及任何新的記錄最新的軟件包安裝已添加。 – haim770

回答

3

ControllerActivator無法實例化您的HomeController,因爲它的構造函數未標記爲public(因此它實際上是private)。

當你不提供任何構造可言,編譯器會自動創建一個public一個給你,但因爲你提供一個(不是public)你沒有公共構造結束了。

試試這個:

public HomeController(IExample injected) 
{ 
    instance = injected; 
} 

更新:

根據您的編輯與API集成控制器的團結,你必須安裝Unity.WebAPI軟件包。

更多的WebAPI inegration:http://www.asp.net/web-api/overview/advanced/dependency-injection

+0

我引用了錯誤的Unity包 - 現在使用Unity.WebAPI包進行MVC Web API項目。謝謝!! –