简单的Injector Web Api控制器构造函数注入失败 [英] Simple Injector Web Api Controller Constructor Injection Failing

查看:144
本文介绍了简单的Injector Web Api控制器构造函数注入失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试实例化注入的控制器时,我的Web Api应用程序失败.我正在使用简单喷射器.自举注入器如下:

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>();
        }
    }
}

正在注入控制器.

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";
        }
    }
}

我一直收到的错误是:

<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>

在配置 Simple Injector 时我缺少什么?

推荐答案

具有WebActivator.PostApplicationStartMethod属性的程序集必须与启动项目的输出目录(即您的webapi/bin)位于同一目录中

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)

由于尚未将Autofac设置为依赖项解析器,因此无法正确构造控制器-从未调用过Initialize函数,因为未加载程序集)

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)

这篇关于简单的Injector Web Api控制器构造函数注入失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆