title: How to inject dbcontext with StructureMap and WebApi2
body: <p>I would like to inject my dbcontext into my services in web api 2 project.  But I’m a little unsure of how to do that.  I've read through the docs but lifecycles, scopes, requests, nested containers...they all leave me a little unsure.  I have pieced together the following code from my best understanding.  After installing the Nuget package StructureMap.WebApi2, I proceeded to update SM from v3 to v4, as well as the SM.MVC5 from v3 to v4.</p>
  
  <p>The following code appears to have the desired effect of using one dbcontext per http request (I think that's what i want...i'm so confused about scopes) so that the same dbcontext is shared for all services during a users transaction, and then disposed when the transaction (http request) is closed. But appearances are not always right.</p>
  
  <p>IoC.cs</p>
  
  <pre><code>    public static IContainer Initialize()
      {
          var container = new Container(_ =&gt;
          {
              _.AddRegistry&lt;DefaultRegistry&gt;();
              _.ForConcreteType&lt;MyDbContext&gt;().Configure.ContainerScoped();
          });
          DomainEvents.Initialize(container);
          return container;
      }}
  </code></pre>
  
  <p>DefaultRegistry.cs:</p>
  
  <pre><code>    public DefaultRegistry()
      {
          var mapperConfig = new MapperConfiguration(cfg =&gt;
          {
              cfg.AddProfile(new Common.Map.MapProfile());
              cfg.CreateMissingTypeMaps = true;
          });
          var mapper = mapperConfig.CreateMapper();
          For&lt;IMapper&gt;().Use(() =&gt; mapperConfig.CreateMapper());
          For&lt;MyDbContext&gt;().Use(()=&gt; new MyDbContext());
  
          Scan(
              scan =&gt;
              {
                  scan.AssemblyContainingType&lt;ServiceBase&gt;();
                  scan.TheCallingAssembly();
                  scan.WithDefaultConventions();
                  scan.ConnectImplementationsToTypesClosing(typeof(IHandle&lt;&gt;));
              });
      }
  </code></pre>
  
  <p>The Nuget package StructureMap.WebApi2 created some other files for wiring up resolution and nested containers, but i'm leaving them out of this question for the sake of brevity.</p>