我的ASP.Net MVC 4 Web API控制器不能與Unity.WebApi一起使用。在同一個項目中,簡單的控制器可以正確使用Unity.Mvc3。但是,當我運行從ApiController衍生我得到一個消息的Web API控制器:ASP.Net MVC 4 Web API控制器不能使用Unity.WebApi
{ 「的$ id」: 「1」, 「消息」: 「發生錯誤」, 「ExceptionMessage」:」類型 'ElectricTests.Controllers.Api.DocumentsController'沒有 默認 構造函數「,」ExceptionType「:」System.ArgumentException「,」StackTrace「:」 at System.Linq.Expressions.Expression.New(Type type個)\ r \ n在 System.Web.Http.Internal.TypeActivator.Create [TBASE](類型 instanceType個)\ r \ n在 System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage 請求,控制器類型型,Func`1 &活化劑)\ r \ n在 System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage 請求,HttpControllerDescriptor controllerDescriptor,類型 controllerType)「}
我ApiController:
public class DocumentsController : ApiController
{
private readonly IDocumentsRepository _repository;
public DocumentsController(IDocumentsRepository repository) {
_repository = repository;
}
public IEnumerable<FormattedDocument> GetFormattedDocuments()
{
return _repository.GetAllFormattedDocuments();
}
...
Bootstrapper.cs:
public static class Bootstrapper {
public static void Initialise() {
IUnityContainer container = BuildUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
private static IUnityContainer BuildUnityContainer() {
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>();
container.RegisterType<IDocumentsRepository, DocumentsRepository>();
container.RegisterType<IQuestionsRepository, QuestionsRepository>();
container.RegisterType<ITestRepository, TestsRepository>();
return container;
}
}
哪裏是我的錯?
異常文本:DocumentsController沒有默認構造函數 – 2013-04-21 14:45:02
本文解決的這個問題: http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency -resolver – Oblomingo 2013-04-22 06:18:00