【发布时间】:2015-03-29 15:17:38
【问题描述】:
我遇到了与described here 相同的问题,我的设置几乎是identical to this,实际上是基于this guide。当我访问控制器中的方法时,我得到了这个
尝试创建类型控制器时出错 '测试控制器'。确保控制器具有无参数 公共构造函数。
这是堆栈跟踪
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator
.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor,
Type controllerType)\r\n
at System.Web.Http.Controllers.HttpControllerDescriptor
.CreateController(HttpRequestMessage request)\r\n
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
这是内部异常的堆栈跟踪
at System.Linq.Expressions.Expression.New(Type type)\r\n
at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator
.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator
.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
这是我的控制器的样子
public class TestController : ApiController
{
private readonly ITestRepo _repo;
public TestController(ITestRepo repo)
{
_repo = repo;
}
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
public string Get(int id)
{
return _repo.GetId(id);
}
}
这就是我设置简单注射器的方法
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Create the container as usual.
var container = new Container();
// Register your types, for instance using the RegisterWebApiRequest
// extension from the integration package:
container.RegisterWebApiRequest<ITestRepo, TestRepo>();
container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
container.Verify();
GlobalConfiguration.Configuration.DependencyResolver =
new SimpleInjectorWebApiDependencyResolver(container);
//
ConfigureOAuth(app, container);
var config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);
}
}
【问题讨论】:
-
从堆栈跟踪看来,Simple Injector 在解析控制器时不参与。检查
GlobalConfiguration.Configuration.DependencyResolver在运行时的值。它很可能在某处被重置。你需要找出发生这种情况的地方。也许在WebApiConfig.Register或app.UseWebApi方法中? -
我认为它是“参与”的,因为当调用“container.Verify”时,每个控制器的 ctor 都会被命中。如果我理解正确,那就是“验证”的用途。
-
这是不正确的。虽然 Verify 会遍历所有注册并检查是否可以创建,但您需要将默认的 Web API 控制器创建机制重定向到 Simple Injector。这就是
SimpleInjectorWebApiDependencyResolver的用途。 Web API 将使用此解析器为每个请求创建一个控制器。但是如果有其他东西改变了这个解析器(或者决定使用不同的解析器),Simple Injector 将不会被要求创建一个控制器,你将回退到 Web API 的默认行为。 -
“验证将遍历所有注册并检查是否可以创建它们”....“Web API 将使用此解析器为每个请求创建一个控制器”....这是我的理解, 我正是这个意思。但是谢谢你说得更清楚。
标签: c# asp.net-web-api2 owin simple-injector