【问题标题】:Simple Injector Web Api Controller Constructor Injection Failing简单注入器 Web Api 控制器构造函数注入失败
【发布时间】:2014-09-04 23:42:24
【问题描述】:

我的 Web Api 应用程序在尝试实例化注入的控制器时失败。我正在使用简单的注射器。引导注入器如下:

[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 时遗漏了什么?

【问题讨论】:

  • 你能发布完整的堆栈跟踪吗?

标签: c# asp.net asp.net-web-api simple-injector


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多