Inject DbContext with Autofac

autofac entity-framework

Question

The entity framework context I have is as follows:

public class Context : DbContext, IDbContext {
}

where the following is the IDbContext:

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

How should DbContext injection be configured while using Autofac?

What I had using StructureMap was as follows:

For<IDbContext>().Use(x => new Context());
1
11
4/10/2015 11:28:11 AM

Accepted Answer

Numerous ways, based on the breadth you require, conventions, etc.

Example:

containerBuilder
  .RegisterType<Context>()
  .AsImplementedInterfaces()
  .InstancePerLifetimeScope();
14
4/10/2015 12:05:29 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow