Search code examples
c#.netasp.net-coredbcontext

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


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 administrator powers to be able to add and delete books from the website.

I've created the login system and database, and 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...

File 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; }
}

File 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?}");
        });
    }

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

File 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; }
}

Solution

  • I fixed this error by specifying --project and --startup-project options to Entity Framework 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 database connection information and other information.