簡體   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