Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject DbContext with Autofac

I have the following EntityFramework context:

public class Context : DbContext, IDbContext {
}

Where IDbContext is the following:

public interface IDbContext {
  DbEntityEntry Entry(Object entity);
  IEnumerable<DbEntityValidationResult> GetValidationErrors();
  Int32 SaveChanges();
  Task<Int32> SaveChangesAsync();
  Task<Int32> SaveChangesAsync(CancellationToken cancellationToken);
  DbSet Set(Type entityType);
  DbSet<TEntity> Set<TEntity>() where TEntity : class;
} // IDbContext

What is the correct way to configure DbContext injection with Autofac?

With StructureMap I had the following:

For<IDbContext>().Use(x => new Context());
like image 361
Miguel Moura Avatar asked Apr 10 '15 11:04

Miguel Moura


Video Answer


1 Answers

Many ways, depending on scope you need, conventions etc.

Example:

containerBuilder
  .RegisterType<Context>()
  .AsImplementedInterfaces()
  .InstancePerLifetimeScope();
like image 150
Jacek Gorgoń Avatar answered Oct 04 '22 01:10

Jacek Gorgoń