Unity IoC does not inject dependency into Web API Controller

前端 未结 4 2006
北荒
北荒 2020-12-18 18:50

I\'m very new to using Unity, but my problem is that whenever I call my web service, I get an exception stating that

\"Make sure that the controller has a parameterl

4条回答
  •  时光取名叫无心
    2020-12-18 19:34

    So, after hours of banging my head against a wall, I've found that this wasn't working because I had an OWIN/Katana Startup.cs class in my project. Now I don't know exactly what's going on here, so any more information would be great.

    Basically, since I was using OWIN/Katana, I had a Startup.cs file that created a new HttpConfiguration object and configured it, similar to how it's done in the WebApiConfig.cs class.

    private void ConfigureWebApi(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
        var container = new UnityContainer();
        container.RegisterType();
        config.DependencyResolver = new UnityDependencyResolver(container);
    
        var jsonFormatter = config.Formatters.OfType

    It looks like the code first runs through the WebApiConfig's Register function, and THEN overrides that HttpConfiguration object with the one generated in the Startup.cs file. I had to move my container setup stuff here in order for it to work.

    Sorry that I didn't bring up the OWIN stuff before. This is fairly new to me and I didn't realize it was relevant. Hopefully this saves someone else the pain that I've just been through.

提交回复
热议问题