3

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?

3 Answers 3

6

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.

2
  • Thanks for this. I just got burned by the same terribly misleading error message.
    – Nick Cox
    Aug 23, 2012 at 14:09
  • 1
    If you make your constructor take no arguments and instead use ObjectFactory.GetInstance<> then structuremap will give you a more helpful error message. Then change it back once you've fixed the problem.
    – John Fouhy
    Mar 4, 2013 at 1:25
0

It's clear that the DI is not called to provide a controller instance but I don't know why. Have you tried setting a debug break point in the structure map code provided by the post (i.e. the code that lives on github) to make sure that it is called?

0

If you hit this error on some controllers, but not others it is likely a different issue.

To get better exception information, add a try / catch in the GetService method override in your implementation of IDependencyScope and set a break point in the catch block. You'll be able to get better debug info.

I know OP already got an answer, this is just for anyone else who stumbles across this and finds it useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.