簡體   English   中英

如何使用 Autofac 為 DbContext 注冊參數?

[英]How do I register a parameter for a DbContext with Autofac?

我正在使用實體框架和 Sql 來處理數據庫。

我的上下文 class 是:

 public class AnimalBreedsContext : DbContext
 {
        public DbSet<AnimalBreed> AnimalBreeds { get; set; }

        public AnimalBreedsContext(DbContextOptions<AnimalBreedsContext> options) : base (options)
        {

        }
  }

class AnimalBreeds 是一個 class 具有一些字符串屬性,如名稱等。

現在我想用 Autofac 注冊 AnimalBreedsContext class。 我嘗試過這樣的事情:

class ContainerConfig
 {
     public static IContainer Configure()
     {
         var builder = new ContainerBuilder(); 

         var options = new DbContextOptionsBuilder<AnimalBreedsContext>()
                         .UseSqlServer("configString")
                         .Options;

         builder.RegisterType<AnimalBreedsContext>().WithParameter(options).AsSelf();

         return builder.Build();
      }
 }

但問題是“參數選項無法從 AnimalBreedsContext 轉換為 Autofac.Parameter”。

有沒有其他選項可以讓我用 Autofac 注冊這個 class?

看起來您沒有向 WithParameter 提供正確的WithParameter 這是顯示所有重載的 Autofac 文檔

如果不將參數包裝在一個 Autofac Parameter對象中,看起來您可以提供參數的字符串名稱作為第一個參數,然后提供實際參數 object 作為第二個參數:

builder.RegisterType<AnimalBreedsContext>()
       .AsSelf()
       .WithParameter("options", options);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM