Simple Injector Web Api Controller Constructor Injection Failing

你离开我真会死。 提交于 2019-12-10 23:37:12

问题


My Web Api app is failing when trying to instantiate an injected controller. I'm using Simple Injector. Bootstrapping the injector is as follows:

[assembly: WebActivator.PostApplicationStartMethod(typeof(SimpleInjectorWebApiInitializer), "Initialize")]

namespace WebApi
{
    using System.Web.Http;
    using SimpleInjector;
    using SimpleInjector.Integration.WebApi;

    public static class SimpleInjectorWebApiInitializer
    {
        public static void Initialize()
        {                
            var container = new Container();
            InitializeContainer(container);
            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
            container.Verify();

            GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
        }

        private static void InitializeContainer(Container container)
        {
            container.RegisterWebApiRequest<ISomething, Something>();
        }
    }
}

The controller being injected.

namespace WebApi.Controllers
{
    using System.Web.Http;

    public class SomethingController : ApiController
    {
        private readonly ISomething _something;

        public SomethingController(ISomething something)
        {
            _something = something;
        }

        public string Get()
        {
            return "Hello world";
        }
    }
}

The error I keep getting is:

<Error>
    <Message>An error has occurred.</Message>
    <ExceptionMessage>
    An error occurred when trying to create a controller of type 'SomethingController'. Make sure that the controller has a parameterless public constructor.
    </ExceptionMessage>
    <ExceptionType>System.InvalidOperationException</ExceptionType>
</error>

What am I missing in configuring Simple Injector?


回答1:


The assembly with the attribute WebActivator.PostApplicationStartMethod needs to be present in the same directory as the startup project's output directory (i.e. your webapi/bin)

The controller couldn't be constructed properly because Autofac hasn't been set up as the dependency resolver - the Initialise function was never called as the assembly wasn't loaded)



来源:https://stackoverflow.com/questions/25676617/simple-injector-web-api-controller-constructor-injection-failing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!