title: Using DbContextScopeFactory with Unity
body: <p>I was trying to use the <a href="http://mehdi.me/ambient-dbcontext-in-ef6/" rel="nofollow">DBContextScopeFactory</a> and running into an issue.</p>
  
  <pre><code>public class VendorRepository : IVendorRepository
  {
      private readonly IDbContextScopeFactory _dbContextScopeFactory;
  
      public VendorRepository(IDbContextScopeFactory dbContextScopeFactory)
      {
          if (dbContextScopeFactory == null)
          {
              throw new ArgumentNullException("dbContextScopeFactory");
          }
          _dbContextScopeFactory = dbContextScopeFactory;
      }
      public IList&lt;MyVendor&gt; GetMyVendors(int requestorId)
      {
          IList&lt;MyVendor&gt; vndrsList = null;
          using (var dbContextScope = _dbContextScopeFactory.CreateReadOnly())
      {
              var dbContext = dbContextScope.DbContexts.Get&lt;VendorMgmtContext&gt;();
              var vndrs = (from a in dbContext.sp_GetVendorByRequestor(requestorId)
                       select new MyVendor
                       {
                           VendorId = a.VendorId,
                           VendorName = a.VendorName,
                           CreatedByUserId = a.CreatedByUserId,
                           CreatedDate = a.CreatedDate
                           });
              vndrsList = vndrs.ToList();
          }
          return vndrsList;
      }
  </code></pre>
  
  <p>}</p>
  
  <p>Unit Testing works great since it was similar to the Demo Application project.  (in other words, I was not registering it in the UnityConfig.cs file.</p>
  
  <pre><code>[TestMethod]
  public void GetMyVendors()
  {
      // Arrange
      var dbContextScope = new DbContextScopeFactory();
      var db = new VendorMgmtContext();
      VendorRepository repository = new VendorRepository(dbContextScope);
      IEnumerable&lt;MyVendor&gt; myVendor = null;
  
      // Act
      myVendor = repository.GetMyVendors(3);
  
      // Assert
      Assert.IsNotNull(myVendor);
  }
  </code></pre>
  
  <p>So now I'm not quite sure how to register this in the UnityConfig.cs file
  I tried:</p>
  
  <pre><code>container.RegisterType&lt;IAmbientDbContextLocator, AmbientDbContextLocator&gt;();
  container.RegisterType&lt;IDbContextScopeFactory, DbContextScopeFactory&gt;();
  container.RegisterType&lt;VendorMgmtContext, VendorMgmtContext&gt;(new PerResolveLifetimeManager(), new InjectionConstructor());
  container.RegisterType&lt;IVendorRepository, VendorRepository&gt;(new PerResolveLifetimeManager());
  container.RegisterType&lt;IVendorService, VendorService&gt;(new PerResolveLifetimeManager());
  </code></pre>
  
  <p>But I received a server error: "The type IDbContextFactory does not have an accessible constructor. "</p>
  
  <p>I also tried:</p>
  
  <pre><code>container.RegisterType&lt;IAmbientDbContextLocator, AmbientDbContextLocator&gt;();
  container.RegisterType&lt;IDbContextScopeFactory, DbContextScopeFactory&gt;(new InjectionFactory((a) =&gt; new DbContextScopeFactory()));
  </code></pre>
  
  <p>and also received errors.  I'm pretty sure it's the way I'm registering this new implementation.  Thank you in advance for your help.</p>
  
  <p><strong>Update:</strong> Error with registering:</p>
  
  <pre><code>container.RegisterType&lt;IDbContextScopeFactory, DbContextScopeFactory&gt;(new InjectionFactory((a) =&gt; new DbContextScopeFactory()));
  
  Message: "An error occurred when trying to create a controller of type 'VendorController'. Make sure that the controller has a parameterless public constructor"
  ExceptionType: System.InvalidOperationException
  StackTrace:
  at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
  at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)
  at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
  at System.Web.Http.Dispatcher.HttpControllerDispatcher.&lt;SendAsync&gt;d__0.MoveNext()
  InnerException:
  Message: "Type 'Portal.Controllers.Api.VendorController' does not have a default constructor"
  ExceptionType: System.ArgumentException
  StackTrace:
  at System.Linq.Expressions.Expression.New(Type type)
  at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)
  at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1&amp; activator)
  at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
  </code></pre>
  
  <p>Update #2 - updated 'Unity.AspNet.WebApi 3.5.1404.0' &amp; Updated Unity from 'Unity 3.0.1304.1' to 'Unity 3.5.1404.0'  I also moved all the registration from the WebApiConfig.cs to the UnityConfig.cs file.  Lastly, I modified the Global.asax.cs from  </p>
  
  <pre><code> UnityConfig.RegisterComponents();
  </code></pre>
  
  <p>to </p>
  
  <pre><code> UnityWebApiActivator.Start();
  </code></pre>
  
  <p>Finally my webAPI is working.  Yet, I am still getting the same exception on the MVC side.</p>
  
  <p>[MissingMethodException: No parameterless constructor defined for this object.]
     System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean&amp; canBeCached, RuntimeMethodHandleInternal&amp; ctor, Boolean&amp; bNeedSecurityCheck) +0
     System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark&amp; stackMark) +119
     System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark&amp; stackMark) +232
     System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
     System.Activator.CreateInstance(Type type) +11
     System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +110</p>
  
  <p>[InvalidOperationException: An error occurred when trying to create a controller of type 'Portal.Controllers.VendorController'. Make sure that the controller has a parameterless public constructor.]
     System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +247
     System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +437
     System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +257
     System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController&amp; controller, IControllerFactory&amp; factory) +326
     System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +157
     System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88
     System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50
     System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103
     System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +155</p>
  
  <p>I do have a constructor</p>
  
  <pre><code>public class VendorController : Controller
  {
      IVendorService _VendorService;
  
      public VendorController(IVendorService VendorSvc)
      {
          _VendorService = VendorSvc;
      }
  
      // GET: Vendor
      public ActionResult Index()
      {
          return View();
      }
  }
  </code></pre>