Injecting a Unit of Work and Service into a Web Api Controller using Autofac?

Jun 10, 2015 at 7:02 PM
Here is my controller.
public class AccountClassesController : ApiController
{
    private readonly IUnitOfWorkAsync _uow;
    private readonly IAccountClassService _accountClassService;

    public AccountClassesController(
        IUnitOfWorkAsync uow,
        IAccountClassService accountClassService)
    {
        _uow = uow;
        _accountClassService = accountClassService;
    }
    //omitted for brevity
}
In my Global.asax.cs file here is how I register everything:
private static void ConfigureDependencyInjection()
{
    var builder = new ContainerBuilder();

    // Get your HttpConfiguration.
    var config = GlobalConfiguration.Configuration;

    // Register your Web API controllers.
    builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

    // OPTIONAL: Register the Autofac filter provider.
    builder.RegisterWebApiFilterProvider(config);

    builder.RegisterType<RedStripeDbContext>().As<IDataContextAsync>().InstancePerRequest();
    builder.RegisterType<UnitOfWork>().As<IUnitOfWorkAsync>().InstancePerRequest();
    builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepositoryAsync<>)).InstancePerRequest();

    builder.RegisterAssemblyTypes(typeof(AccountService).Assembly)
        .Where(t => t.Name.EndsWith("Service"))
        .As(t => t.GetInterfaces().FirstOrDefault(
            i => i.Name == "I" + t.Name)).InstancePerRequest();

    // Set the dependency resolver to be Autofac.
    var container = builder.Build();

    config.DependencyResolver = new AutofacWebApiDependencyResolver(container);            
}
Finally here is a post method. I'm injecting the UoW into the controller to have the fine grained control you speak of in other posts.
public IHttpActionResult Put(int accountClassId, [FromBody] AccountClass accountClass)
{
    try
    {
        if (accountClass == null || accountClassId != accountClass.AccountClassId)
            return BadRequest();

        _accountClassService.Update(accountClass);
        int changeCount = _uow.SaveChanges();

        if (changeCount > 0)
            return Ok(accountClass);

        return NotFound();
    }
    catch (Exception)
    {
        return InternalServerError();
    }
}
Does my DI setup seem correct? I am wondering because when I debug, the UoW never has any repositories. However, when I call .SaveChanges on the UoW, everything seems to be working. Any reassurance is much appreciated. Thanks.