I am trying to use AppDbContext
(belongs to entity framework core), in one of my classes and instantiate it with autofac, here's how it looks like:
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; }
}
I am having a hard time fully understanding on how to implement this correctly.could anyone throw a bone?
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();
this is the error that I am getting.
DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'JobsImpl.DailyCleanUpJob' can be invoked with the available services and parameters: Cannot resolve parameter 'Utils.AppDbContext context' of constructor 'Void .ctor(Utils.AppDbContext)'.
A friend helped me out with this one:
If you're facing the same issue here is the code:
var contextOptions = new DbContextOptionsBuilder<AppDbContext>().Options;
//... configure options as necessary
builder.RegisterInstance(contextOptions).As<DbContextOptions<AppDbContext>>();
builder.RegisterType<IdentityDbContext>();
builder.RegisterType<AppDbContext>();
Because the constructor of AppDbContext
is receiving an instance of DbContextOptions<AppDbContext>
you need to instantiate it fist, then register the instance as DbContextOptions<AppDbContext>
.