I am using the Unity.WebApi NuGet package (Unity 4.0.1 and Unity.WebApi 5.2.3) in an ASP.NET WebApi solution. The issue I am facing is that when attempting to run the code, I get the error: Make sure that the controller has a parameterless public constructor
. I've searched similar threads here, but I couldn't find any thread that matched my issue.
Please don't just say "Add a parameterless constructor" because it shows you obviously have no clue what IoC is and why that statement makes absolutely no sense and defeats the purpose of IoC. I say this because I saw this on a lot of the other threads I've looked at thus far.
This is my Startup.cs (I'm using Owin, so I do not have a Global.asax):
public void Configuration(IAppBuilder app) {
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
// Registering unity stuff
UnityConfig.RegisterComponents();
app.UseWebApi(config);
}
This is my 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);
}
}
This is my API Controller:
public class MyController : ApiController {
private IService service
public MyController(IService service) {
this.service = service;
}
public IHttpActionResult Get() {
return Ok("All systems go!");
}
}
EDIT
I took the using statements out because people are having a hard time understanding that the issue occurs whether or not the using statements are there.
var container = new UnityContainer()
out of the using block. – Phytohormone