Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Web API & StructureMap: "does not have a default constructor"

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?

like image 685
Petrus Theron Avatar asked Feb 19 '26 18:02

Petrus Theron


1 Answers

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.

like image 61
Petrus Theron Avatar answered Feb 21 '26 13:02

Petrus Theron