ASP.NET MVC Web API和StructureMap:"没有默认构造函数"

Pet*_*ron 3 structuremap asp.net-mvc dependency-injection asp.net-web-api

我配置了一个ASP.NET MVC 4的Web API项目使用StructureMap 2.6.2.0中描述的这个帖子,但访问/api/parts返回下面的错误,尽管显式调用StructuremapMvc.Start();Application_Start():

{
  "ExceptionType": "System.ArgumentException",
  "Message": "Type 'MyProject.Web.Controllers.PartsController' does not have
              a default constructor",
  "StackTrace": "   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.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
}
Run Code Online (Sandbox Code Playgroud)

我实现IDependencyResolverIDependencyScope设置了Web API依赖关系解析器,如下所示~/App_Start/StructureMapMvc.cs:

GlobalConfiguration.Configuration.DependencyResolver =
    new StructureMapHttpDependencyResolver(container);
Run Code Online (Sandbox Code Playgroud)

为什么Web API仍然抱怨默认的consturctor?

Pet*_*ron 6

原来错误描述真的很糟糕.正在调用StructureMap,但由于缺少连接字符串,因此无法注入依赖构造函数参数.

以下是我修复它的方法IoC.cs:

x.For(typeof(IRepository<>)).Use(typeof(MongoRepository<>))
    .CtorDependency<string>("connectionString")
    .Is(yourConnectionString);
Run Code Online (Sandbox Code Playgroud)

我这样做(错误地):

x.For<IRepository<SomeEntity>>().Use<MongoRepository<SomeEntity>>();
Run Code Online (Sandbox Code Playgroud)

确实应该有一种在Web API中出现时输出内部StructureMap异常的方法.