我在ASP.NET WebApi解决方案中使用Unity.WebApi NuGet包(Unity 4.0.1和Unity.WebApi 5.2.3).我面临的问题是,在尝试运行代码时,我收到错误:Make sure that the controller has a parameterless public constructor.我在这里搜索过类似的帖子,但我找不到任何符合我问题的帖子.
请不要只说"添加无参数构造函数",因为它显示您显然不知道IoC是什么以及为什么该语句完全没有意义并且违背了IoC的目的.我之所以这么说是因为我在迄今为止看过的很多其他主题中看到了这一点.
这是我的Startup.cs(我使用的是Owin,所以我没有Global.asax):
public void Configuration(IAppBuilder app) {
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
// Registering unity stuff
UnityConfig.RegisterComponents();
app.UseWebApi(config);
}
Run Code Online (Sandbox Code Playgroud)
这是我的UnityConfig.cs:
public static class UnityConfig {
public static void RegisterComponents() {
var container = new UnityContainer();
// Register controller
container.RegisterType<MyController>();
// Register interface
container.RegisterType<IService, Service>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的API控制器:
public class MyController : ApiController {
private IService service
public MyController(IService service) …Run Code Online (Sandbox Code Playgroud) c# dependency-injection inversion-of-control unity-container asp.net-web-api
这是手头的问题:
在调用我CustomerController的时候URL,我得到以下异常:
ExceptionMessage:
尝试创建"CustomerController"类型的控制器时发生错误.确保控制器具有无参数的公共构造函数.
我使用以下网址:
请注意:
/api/Customer/在我将逻辑重构为业务类并实现依赖注入之前,调用正在进行.
我的研究表明,我没有正确地注册我的界面和课程Ninject,但不确定我错过了哪一步.
研究链接:
这是我的问题导致此异常的原因是什么?我正在注册我的接口/类
Ninject,但它似乎没有正确识别映射.有什么想法吗?
客户控制员
public class CustomerController : ApiController
{
private readonly ICustomerBusiness _customerBusiness;
public CustomerController(ICustomerBusiness customerBusiness)
{
_customerBusiness = customerBusiness;
}
// GET api/Customer
[HttpGet]
public IEnumerable<Customer> GetCustomers()
{
return _customerBusiness.GetCustomers();
}
// GET api/Customer/Id
[HttpGet]
public IEnumerable<Customer> GetCustomersById(int customerId)
{
return _customerBusiness.GetCustomerById(customerId);
}
}
Run Code Online (Sandbox Code Playgroud)
客户业务
public class CustomerBusiness : ICustomerBusiness
{
private readonly DatabaseContext …Run Code Online (Sandbox Code Playgroud)