'Unable to resolve service for type ¨Microsoft.entityFrameworkCore.DbContextOptions¨1[LibraryData.LibraryContext] while attempting to activate

Viewed 8924

I've run into a problem i cannot solve on my own, so I'm asking for help.

I've recently began learning ASP .net core, and wanted to build a library where i have to have a database, login system and admin powers to be able to add and delete books from the website.

I've created the login system and database, now i want to add the CRUD to the project, but this error pops up

"'Unable to resolve service for type ¨Microsoft.entityFrameworkCore.DbContextOptions¨1[LibraryData.LibraryContext] while attempting to activate "LibraryData.LibraryContext"

This is my code so far...

LibraryData.LibraryContext.cs

public class LibraryContext : DbContext
    {
        public LibraryContext(DbContextOptions<LibraryContext> options) : base(options)
        {

        }

        public DbSet<User> Users { get; set; }
        public DbSet<Video> Videos { get; set; }
        public DbSet<BranchHours> BranchHour { get; set; }
        public DbSet<Checkout> checkouts { get; set; }
        public DbSet<CheckoutHistory> checkoutHistorys { get; set; }
        public DbSet<Holds> holds { get; set; }
        public DbSet<LibraryAsset> LibraryAssets { get; set; }
        public DbSet<Book> Books { get; set; }
        public DbSet<LibraryBranch> libraryBranches { get; set; }
        public DbSet<LibraryCard> LibraryCards { get; set; }
        public DbSet<Status> statuses { get; set; }
    }

Startup.cs

        public IConfiguration Configuration { get; }       
        
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddMvc().AddSessionStateTempDataProvider();
            services.AddDistributedMemoryCache();
            services.AddSession();
            services.AddSingleton(Configuration);
            services.AddScoped<ILibraryAsset, LibraryAssetService>();
            services.AddControllersWithViews();
            services.AddDbContext<LibraryContext>(options
                 => options.UseSqlServer(Configuration.GetConnectionString("LibraryConnection")));
            services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<LibraryContext>();
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
            services.AddScoped<DbContext, LibraryContext>();
            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        }

               public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSession();
            app.UseRouting();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

Program.cs

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

AssetIndexListingModel.cs

    public class AssetIndexListingModel
    {
        public int Id { get; set; }
        public string ImageUrl { get; set; }
        public string Title { get; set; }
        public string AuthorOrDirector { get; set; }
        public string Type { get; set; }
        public string DeweyCallNumber { get; set; }
        public string NumberOfPages { get; set; }
        public int DateOfRealease { get; set; }
        public int AgeRes { get; set; }
        public string About { get; set; }
    }
5 Answers

I fixed this error by specifying --project and --startup-project options to EF Core CLI tools like this:

dotnet ef database update --verbose --project CommandService.Data   --startup-project CommandService

--project means which project contains the DbContext class

--startup-project means which project contains the Db connection info and other information.

I recently ran into this issue myself, and this is how I resolved the issue. In Startup.cs (Configure Services)

public void ConfigureServices(IServiceCollection services)
{
    //Some Code
    services.AddDbContext<LibraryContext>();
    //Some Code
} 

and then in your DbContext class instead on passing the DbContextOptions to your base class, configure them as follows.

public LibraryContext()
{
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer("Your Connection String");
}

Try to modify your context:

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

        }

to

public LibraryContext(DbContextOptions options)
: base(options)
{
}

Refer to this document:

https://github.com/dotnet/efcore/issues/15145

You should add a code which tells how tools should create DBContext. It is needed when you have DBContext in the class library project referenced to the web project.

public class BloggingContextFactory : IDesignTimeDbContextFactory<BloggingContext>
{
    public BloggingContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
          optionsBuilder.UseNpgsql();

        return new BloggingContext(optionsBuilder.Options);
    }
}
Related