我正在构建一个非常简单的控制器集,我想注入依赖项。MVC Web API和用于依赖项注入的Unity
我的Web Api项目正在使用.net 4.5.1(vs2015),我正在使用Unity进行依赖注入(对于Unity来说真的很新)。
这是我做了什么:
- 新建项目> ASP.Net网机应用>网络API项目(无身份验证)
- 工具> NuGet包管理器>管理的解决方案包... 搜索“Unity.MVC”并安装软件包。
我创建了以下接口和类:
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有这两个新增加的文件:
我下面的代码添加到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)"
}
}
在此先感谢!
出于某种原因,由匿名用户的承诺,它不会显示出来,除非批准更多的一个用户你的编辑标记。 – haim770
根据你的(还有提议)更新,你只安装了'Unity.Mvc',它负责与MVC的'DependecyResolver'集成。对于WebApi,您必须安装Unity.WebAPI包:https://www.nuget.org/packages/Unity.WebAPI – haim770
显示您的'WebApiConfig.cs'和'UnityMvcActivator.cs'以及任何新的记录最新的软件包安装已添加。 – haim770