title: Unable to inject DBContext into my Web API 2 Controller with Unity
body: <p>I've been at it for days, but I can't get Unity to inject anything with <code>RegisterType&lt;&gt;</code> into my <code>Controller</code>. I'm using Web Api 2, in Visual Studio 2015, with Unity 4. Whenever I try to inject <code>IUnitOfWork</code> or <code>IRFContext</code>, I get   <code>"message": "An error occurred when trying to create a controller of type 'ClPlayersController'. Make sure that the controller has a parameterless public constructor."</code>.
  I'm using the <code>Unity.AspNet.WebApi</code> to bootstrapp into WebApi. Below is my <code>UnityWebApiActivator</code></p>
  
  <pre><code>[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(mycompany.project.api.UnityWebApiActivator), "Start")]
  [assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(mycompany.project.api.UnityWebApiActivator), "Shutdown")]
  
  namespace mycompany.project.api
  {
      public static class UnityWebApiActivator
      {
          public static void Start() 
          {
              var resolver = new UnityDependencyResolver(UnityConfig.GetConfiguredContainer());
              GlobalConfiguration.Configuration.DependencyResolver = resolver;
          }
  
          public static void Shutdown()
          {
              var container = UnityConfig.GetConfiguredContainer();
              container.Dispose();
          }
      }
  }
  </code></pre>
  
  <p>I'm using a Start.cs due to Owin.</p>
  
  <pre><code>[assembly: OwinStartup(typeof(mycompany.project.api.Startup))]
  namespace mycompany.project.api
  {
      public class Startup
      {
          public void Configuration(IAppBuilder app)
          {
              HttpConfiguration config = new HttpConfiguration();
  
              ConfigureOAuth(app);
  
              config.DependencyResolver = new UnityDependencyResolver(UnityConfig.GetConfiguredContainer());
              WebApiConfig.Register(config);
              app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
              app.UseWebApi(config);
          }
  
          public void ConfigureOAuth(IAppBuilder app)
          {
              OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
              {
                  AllowInsecureHttp = true,
                  TokenEndpointPath = new PathString("/token"),
                  AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                  Provider = new SimpleAuthorizationServerProvider(),
                  RefreshTokenProvider = new SimpleRefreshTokenProvider()
              };
  
              // Token Generation
              app.UseOAuthAuthorizationServer(OAuthServerOptions);
              app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
  
          }
      }
  }
  </code></pre>
  
  <p>My <code>WebApiConfig.cs</code> is below:</p>
  
  <pre><code>namespace mycompany.project.api
  {
      public static class WebApiConfig
      {
          public static void Register(HttpConfiguration config)
          {
              log4net.Config.XmlConfigurator.Configure();
              config.MapHttpAttributeRoutes();
              config.EnableSystemDiagnosticsTracing();
              config.Services.Add(typeof(IExceptionLogger),
                  new SimpleExceptionLogger(new LogManagerAdapter()));
              config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
          }
      }
  }
  </code></pre>
  
  <p>My <code>UnityConfig.cs</code> is below</p>
  
  <pre><code>namespace mycompany.project.api
  {
      public class UnityConfig
      {
          #region Unity Container
          private static Lazy&lt;IUnityContainer&gt; container = new Lazy&lt;IUnityContainer&gt;(() =&gt;
          {
              var container = new UnityContainer();
              RegisterTypes(container);
              return container;
          });
  
          public static IUnityContainer GetConfiguredContainer()
          {
              return container.Value;
          }
          #endregion
  
          public static void RegisterTypes(IUnityContainer container)
          {
              var config = new MapperConfiguration(cfg =&gt;
              {
                                  //AutoMapper bindings
              });
              container.RegisterInstance&lt;IMapper&gt;(config.CreateMapper());
              container.RegisterType&lt;IRFContext, RFContext&gt;(new PerThreadLifetimeManager());
              container.RegisterType&lt;IUnitOfWork, UnitOfWork&gt;();
              XmlConfigurator.Configure();
              var logManager = new LogManagerAdapter();
              container.RegisterInstance&lt;ILogManager&gt;(logManager);
          }
      }
  }
  </code></pre>
  
  <p>All that I have in my <code>Global.asax</code> is below:</p>
  
  <pre><code>public class WebApiApplication : System.Web.HttpApplication
  {
      protected void Application_Error()
      {
          var exception = Server.GetLastError();
          if (exception != null)
          {
              var log = new LogManagerAdapter().GetLog(typeof(WebApiApplication));
              log.Error("Unhandled exception.", exception);
          }
      }
  }
  </code></pre>
  
  <p>If my Controller is like this, it works fine:</p>
  
  <pre><code>public class ClPlayersController : ApiController
  {
      private readonly IMapper mapper;
  
      public ClPlayersController(IMapper _mapper, IUnityContainer container)
      {
          mapper = _mapper;
      }
  </code></pre>
  
  <p>But placing IUnitOfWork, like below, or the IRFContext, I get the error:</p>
  
  <pre><code>    private readonly IMapper mapper;
      private readonly IUnitOfWork unitOfWork;
  
      public ClPlayersController(IMapper _mapper, IUnityContainer container, IUnitOfWork _unitOfWork)
      {
          mapper = _mapper;
          unitOfWork = _unitOfWork;
      }
  </code></pre>
  
  <p>I can't find, for the life of me, what I'm doing wrong. If I loop through the <code>container.Registrations</code> on the constructor, I find the mappings, but they refuse to get injected. Any hints?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Below is the code for UnitOfWork and RFContext</p>
  
  <pre><code>namespace mycompany.project.data.configuracao
  {
      public class UnitOfWork : IUnitOfWork
      {
          private readonly IRFContext _rfContext;
          private bool _disposed = false;
  
          public UnitOfWork(IRFContext rfContext)
          {
              _rfContext = rfContext;
          }
          public void Commit()
          {
              if (_disposed)
              {
                  throw new ObjectDisposedException(this.GetType().FullName);
              }
  
              _rfContext.SaveChanges();
          }
          public void Dispose()
          {
              Dispose(true);
              GC.SuppressFinalize(this);
          }
  
          protected virtual void Dispose(bool disposing)
          {
              if (_disposed) return;
  
              if (disposing &amp;&amp; _rfContext != null)
              {
                  _rfContext.Dispose();
              }
  
              _disposed = true;
          }
      }
  }
  </code></pre>
  
  <p>and </p>
  
  <pre><code>namespace mycompany.project.data.configuracao
  {
      public interface IUnitOfWork : IDisposable
      {
          void Commit();
      }
  }
  </code></pre>
  
  <p>and RFContext is a basic POCO generated DBContext</p>
  
  <pre><code>namespace mycompany.project.data.configuracao
  {
      using System.Linq;
  
      public class RFContext : System.Data.Entity.DbContext, IRFContext
      {
          public System.Data.Entity.DbSet&lt;ClGrupoEconomico&gt; ClGrupoEconomicoes { get; set; }
                  //all my DbSets
          public System.Data.Entity.DbSet&lt;SpTipoLog&gt; SpTipoLogs { get; set; }
  
          static RFContext()
          {
              System.Data.Entity.Database.SetInitializer&lt;RFContext&gt;(null);
          }
  
          public RFContext()
              : base("Name=RFContext")
          {
          }
  
          public RFContext(string connectionString)
              : base(connectionString)
          {
          }
  
          public RFContext(string connectionString, System.Data.Entity.Infrastructure.DbCompiledModel model)
              : base(connectionString, model)
          {
          }
  
          public RFContext(System.Data.Common.DbConnection existingConnection, bool contextOwnsConnection)
              : base(existingConnection, contextOwnsConnection)
          {
          }
  
          public RFContext(System.Data.Common.DbConnection existingConnection, System.Data.Entity.Infrastructure.DbCompiledModel model, bool contextOwnsConnection)
              : base(existingConnection, model, contextOwnsConnection)
          {
          }
  
          protected override void Dispose(bool disposing)
          {
              base.Dispose(disposing);
          }
  
          protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
          {
              base.OnModelCreating(modelBuilder);
  
              modelBuilder.Configurations.Add(new ClGrupoEconomicoConfiguration());
                          //all my Configuration classes
              modelBuilder.Configurations.Add(new SpTipoLogConfiguration());
          }
  
          public static System.Data.Entity.DbModelBuilder CreateModel(System.Data.Entity.DbModelBuilder modelBuilder, string schema)
          {
              modelBuilder.Configurations.Add(new ClGrupoEconomicoConfiguration(schema));
                          //all my configuration classes
              modelBuilder.Configurations.Add(new SpTipoLogConfiguration(schema));
              return modelBuilder;
          }
      }
  }
  </code></pre>