12

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());
Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

2 Answers2

17

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

Example:

containerBuilder
  .RegisterType<Context>()
  .AsImplementedInterfaces()
  .InstancePerLifetimeScope();
Jacek Gorgoń
  • 3,206
  • 1
  • 26
  • 43
  • 1
    Gorgon: Is there a reason for using AsImplementedInterfaces() instead of specifying the interface, eg., As? And why not use InstancePerRequest()?Thank You. – Miguel Moura Apr 10 '15 at 12:16
  • 6
    Specifying interface(s) explicitly is fine. It's a matter of taste, conventions, discipline, etc (I prefer automagical stuff with conventions). InstancePerRequest() is fine if you're strictly in a web context, but won't work otherwise. InstancePerLifetimeScope() assumes you're aware of the scope and control it by some means yourself (e.g. create one per thread in a batch job). – Jacek Gorgoń Apr 10 '15 at 12:57
0

Assuming that your constructor expects to receive a DbContext factory Func<IDbContext> so you'll be able to get new instances of DbContext on each call and dispose them on your own, you should use:

builder.RegisterType<Context>().AsImplementedInterfaces().InstancePerDependency().ExternallyOwned();

You might want to take a look at https://autofac.readthedocs.io/en/latest/resolve/relationships.html

Nir
  • 1,836
  • 23
  • 26