尝试实例化注入的控制器时,我的Web Api应用程序失败。我使用Simple Injector。引导注入器如下:
[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
时我缺少什么?
答案 0 :(得分:1)
具有WebActivator.PostApplicationStartMethod属性的程序集需要与启动项目的输出目录(即您的webapi / bin)存在于同一目录中
由于Autofac尚未设置为依赖性解析器,因此无法正确构建控制器 - 由于未加载程序集,因此从未调用过Initialise函数。