使用 Autofac 注入 DbContext [英] Inject DbContext with Autofac

查看:96
本文介绍了使用 Autofac 注入 DbContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 EntityFramework 上下文:

I have the following EntityFramework context:

public class Context : DbContext, IDbContext {
}

其中 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

使用 Autofac 配置 DbContext 注入的正确方法是什么?

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

使用 StructureMap 我有以下几点:

With StructureMap I had the following:

For<IDbContext>().Use(x => new Context());

推荐答案

多种方式,取决于您需要的范围、约定等

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

示例:

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

这篇关于使用 Autofac 注入 DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆