Question

I have a weird situation where StructureMap 2.6.4.1 is reporting a type as not being registered when it clearly is.

In a web api controller I have

    public RedirectToRouteResult GetSlideSet(int id) {
        var whatdoIHave = ObjectFactory.WhatDoIHave();
        var dbctx = ObjectFactory.GetInstance<MyProject.Models.MyDbContext>();
        return RedirectToRoute(WebApiConfig.DefaultRouteName, new {controller="SlideSet", id});
    }

WhatDoIHave reports:

===========================================================================================================
...snip...

MyDbContext(MyProject.Models.MyDbContext)                                                                                                                                                                                                                                                                                                                                                                                                      
Scoped as:  HttpContext

...snip...

This is the only reference to MyDbContext in WhatDoIHave

Yet I get an error when calling GetInstance:

StructureMap.StructureMapException occurred
  HResult=-2146232832
  Message=StructureMap Exception Code:  202
No Default Instance defined for PluginFamily MyProject.Models.MyDbContext, MyProject, Version=2.4.5.25029, Culture=neutral, PublicKeyToken=null
  Source=StructureMap
  ErrorCode=202
  StackTrace:
       at StructureMap.BuildSession.<.ctor>b__0(Type t) in c:\BuildAgent\work\767273992e840853\src\StructureMap\BuildSession.cs:line 33
  InnerException: 

Does anyone know what could be wrong or how even to troubleshoot this?

Edit: To Clarify, MyDbContext absolutely has a parameterless constructor but it also has a non-parameterless one (not that it should matter). I even created a unit test in my test project:

    [Fact]            
    public void get() {
        ObjectFactory.Initialize(x => x.Configure(c => c.Configure(r => r.For<MyDbContext>().HttpContextScoped()) ));
        ObjectFactory.GetInstance<MyDbContext>().ShouldNotBeNull();
    }

Which passes just fine. Oddly enough it was failing for a while in the same manner but then started succeeding while I was trying to narrow down the issue and I couldn't recreate the error. Does structuremap do some sort of system-wide caching?

Was it helpful?

Solution

The issue had to do after all with the fact that MyDbContext had multiple constructors.

MyDbContext() : base() { }
MyDbContext(connectionString) : base(connectionString) { }

Removing the second one fixed the issue in the unit test. This was confounded however by my unit test runner having issues and not being able to run the latest version of the code. I've got that sorted out and can now solve the issue with

For<MyDbContext>().HttpContextScoped().Use(() => new MyDbContext())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top