Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Injector Web Api Controller Constructor Injection Failing

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?

like image 498
Chace Fields Avatar asked Dec 05 '25 19:12

Chace Fields


1 Answers

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)

like image 97
Austin Salonen Avatar answered Dec 07 '25 09:12

Austin Salonen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!