繁体   English   中英

如何在Repository中注入EntityFramework Core DbContext

[英]How to inject EntityFramework Core DbContext in Repository

大多数在线示例处理asp.net并将其DbContext注册为其启动服务注册表的一部分。

我尝试像这样注册我的DbContext

builder.RegisterType<MyContext>()
    .As<MyContext>()
    .InstancePerLifetimeScope();

builder.RegisterType<DealRepository>()
    .Keyed<IRepository<Deal>>(FiberModule.Key_DoNotSerialize)
    .As<IRepository<Deal>>()
    .SingleInstance();

builder.RegisterType<CardsDialog>()
    .As<IDialog<object>>()
    .InstancePerDependency();

但是我收到了这个错误

违反类型的继承安全规则:'System.Net.Http.WebRequestHandler'。 派生类型必须与基本类型的安全可访问性匹配,或者不太容易访问。

它更复杂,因为实际的MessageController.csPost上创建了一个新的范围

using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
{
    var dialog = scope.Resolve<IDialog<object>>();

    await Conversation.SendAsync(activity, () => dialog);

}

如何进行注册?

编辑:正如所建议的那样,使用InstancePerRequest解决了这个问题。 但我也有一个Quartz作业,每X秒运行一次,也需要一个存储库。

builder.RegisterType<DealJob>()
    .AsSelf()
    .SingleInstance();

无法解析类型'BargainBot.Repositories.MyContext',因为无法找到它所属的生命周期范围。 此注册公开了以下服务: - BargainBot.Repositories.MyContext

详细信息--->从请求实例的作用域中看不到带有与“AutofacWebRequest”匹配的标记的作用域。 如果您在执行Web应用程序期间看到这一点,它通常表示SingleInstance()正在请求按HTTP请求注册的组件

我此时应手动解析新的DbContext吗? 或许我应该改变我的回购生命周期?

Edit2:看起来即使删除整个Quartz作业注册,我仍然会收到此错误。

我对这个问题错了,它不是IoC和DbContext问题。 好像它是在.NET平台本身

https://github.com/dotnet/corefx/issues/9846#issuecomment-274707732

添加重定向就可以了

  <dependentAssembly>
    <assemblyIdentity name="System.ComponentModel.TypeConverter" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.0.0" />
  </dependentAssembly>

我遇到了类似的问题,经过大量的来回后,以下代码对我有用:

的DbContext

 public class SalesDbContext : DbContext
{
    public SalesDbContext(DbContextOptions<SalesDbContext> options) : base(options)
    {
    }

    public DbSet<Domain.Product.Product> Products { get; set; }


    protected override void OnModelCreating(ModelBuilder builder)
    {
        // Configure database attributes
    }



}

知识库

 public class ProductRepository : IProductRepository
{
    private readonly SalesDbContext _db;

    public ProductRepository(SalesDbContext db)
    {
        _db = db;
    }


}

Autofac模块

 public class DefaultModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        // Register Entity Framework
        var dbContextOptionsBuilder = new DbContextOptionsBuilder<SalesDbContext>().UseSqlServer("MyConnectionString");

        builder.RegisterType<SalesDbContext>()
            .WithParameter("options", dbContextOptionsBuilder.Options)
            .InstancePerLifetimeScope(); 

    }
}

安装System.Net.Http 4.3.1解决了我的问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM