I configured an ASP.NET MVC 4 Web API project to use StructureMap 2.6.2.0 as described in this post, but accessing /api/parts returns the following error despite explicitly calling StructuremapMvc.Start(); in 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)"
}
I implemented IDependencyResolver and IDependencyScope and set the Web API dependency resolver as follows in ~/App_Start/StructureMapMvc.cs:
GlobalConfiguration.Configuration.DependencyResolver =
new StructureMapHttpDependencyResolver(container);
Why is Web API still complaining about a default consturctor?
Turns out the error description is just really bad. StructureMap is being called, but cannot inject a dependent constructor parameter due to a missing connection string.
Here's how I fixed it in IoC.cs:
x.For(typeof(IRepository<>)).Use(typeof(MongoRepository<>))
.CtorDependency<string>("connectionString")
.Is(yourConnectionString);
I was doing this (incorrectly):
x.For<IRepository<SomeEntity>>().Use<MongoRepository<SomeEntity>>();
There really should be a way to output inner StructureMap exceptions when they occur in the Web API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With