【问题标题】:Injecting AppDbContext with constructor with params exception使用带有参数异常的构造函数注入 AppDbContext
【发布时间】:2020-03-26 19:42:30
【问题描述】:

我正在尝试在我的一个类中使用AppDbContext(属于实体框架核心)并使用autofac对其进行实例化,如下所示:

public class AppDbContext : IdentityDbContext<ApplicationUser>
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Message>().Property(m => m.Service).HasConversion<int>();
        builder.Entity<ApplicationUser>().HasMany<Message>(m => m.Messages).WithOne(u => u.User).IsRequired();
        base.OnModelCreating(builder);
    }


    public DbSet<Message> Messages { get; set; }
    public DbSet<UsersCredentialsModel> UsersCredentialsModels { get; set; }
    public DbSet<CookieModel> CookieModel { get; set; }


}

我很难完全理解如何正确实现这一点。任何人都可以扔骨头吗?

public static IContainer Startup()
{
    var builder = new ContainerBuilder();
   // builder.RegisterType<AppDbContext>().As<IdentityDbContext<ApplicationUser>>().InstancePerRequest();

    builder.RegisterType<Application>().As<IApplication>();
    builder.RegisterType<RabbitMQImpl>().As<IListenerQueue>().SingleInstance();
    builder.RegisterType<BotFactory>().As<IBotFactory>();
    var instance = QuartzInstance.Instance;
    builder.RegisterType<QueueImpl>().AsImplementedInterfaces();
    builder.RegisterType<ConsumerSchechuler>().AsImplementedInterfaces();
    builder.RegisterType<SchedulerImpl>().AsImplementedInterfaces();
    builder.RegisterModule(new QuartzAutofacJobsModule(typeof(ConsumerSchedulerJob).Assembly)).RegisterAssemblyModules();
    builder.RegisterModule(new QuartzAutofacJobsModule(typeof(DailyCleanUpJob).Assembly)).RegisterAssemblyModules();
    builder.RegisterInstance(QuartzInstance.Instance).AsImplementedInterfaces();
    return builder.Build();

这是我遇到的错误。

DependencyResolutionException:在“JobsImpl.DailyCleanUpJob”类型上使用“Autofac.Core.Activators.Reflection.DefaultConstructorFinder”找到的任何构造函数都不能使用可用的服务和参数调用: 无法解析构造函数“Void .ctor(Utils.AppDbContext)”的参数“Utils.AppDbContext context”。

【问题讨论】:

    标签: c# .net-core autofac


    【解决方案1】:

    一位朋友帮我解决了这个问题:

    如果你遇到同样的问题,这里是代码:

    var contextOptions = new DbContextOptionsBuilder<AppDbContext>().Options;
    
    //... configure options as necessary
    
    builder.RegisterInstance(contextOptions).As<DbContextOptions<AppDbContext>>();
    builder.RegisterType<IdentityDbContext>();
    builder.RegisterType<AppDbContext>();
    

    因为AppDbContext的构造函数正在接收DbContextOptions&lt;AppDbContext&gt;实例,所以需要先实例化它,然后将实例注册为DbContextOptions&lt;AppDbContext&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-10
      • 1970-01-01
      • 2021-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      相关资源
      最近更新 更多