如何用Autofac为DbContext注册一个参数?

问题描述 投票:0回答:1

我使用Entity Framework和Sql与数据库合作。

我的上下文类是。

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

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

        }
  }

AnimalBreeds类是一个有一些字符串属性的类,比如Name等。

现在我想用Autofac注册AnimalBreedsContext类。我试了一下这样的东西。

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注册这个类?

c# autofac
1个回答
1
投票

看起来你没有为以下函数提供正确的参数 WithParameter. 以下是Autofac的文档 显示所有的重载。

在没有将参数包装在Autofac的一个 Parameter 对象,看起来你可以提供字符串的 名称 的参数作为第一个参数,然后将你的实际参数对象作为第二个参数。

builder.RegisterType<AnimalBreedsContext>()
       .AsSelf()
       .WithParameter("options", options);
© www.soinside.com 2019 - 2024. All rights reserved.