Inject DbContext with Autofac

橙三吉。 提交于 2019-12-18 15:16:16

问题


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());

回答1:


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

Example:

containerBuilder
  .RegisterType<Context>()
  .AsImplementedInterfaces()
  .InstancePerLifetimeScope();


来源:https://stackoverflow.com/questions/29560294/inject-dbcontext-with-autofac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!