简体   繁体   中英

How do I register a parameter for a DbContext with Autofac?

I am using Entity Framework and Sql to work with a database.

My context class is:

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

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

        }
  }

The class AnimalBreeds is a class that has some string properties like Name, etc.

Now I want to register the AnimalBreedsContext class with Autofac. I tried something like that:

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();
      }
 }

But the problem is that "parameter options can't be converted from AnimalBreedsContext to Autofac.Parameter".

Is there any other option so that I can register this class with Autofac?

It looks like you aren't providing the correct arguments to WithParameter . Here is the Autofac documentation showing all of the overloads.

Without wrapping the argument in one of the Autofac Parameter objects, it looks like you can provide the string name of the parameter as the first argument, then your actual parameter object as the second:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM