skip to Main Content

I am following an Instructor, everything was going smoothly at first, but after I posted the project to github, there were changes in the files of the project, I think I did something wrong, I edited the content later. But there is a point I missed, I think I can’t establish the database connection (or I misunderstand it) I also tried the solutions on the page on this subject, but it didn’t work. Could you please help me?

the error I get is as follows

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Repositories.RepositoryContext Lifetime: Scoped ImplementationType: Repositories.RepositoryContext': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbSet1[Entities.Models.Product]’ while attempting to activate ‘Repositories.RepositoryContext’.) (Error while validating the service descriptor ‘ServiceType: Repositories.Contracts.IRepositoryManager Lifetime: Scoped ImplementationType: Repositories.RepositoryManager’: Unable to resolve service for type ‘Microsoft.EntityFrameworkCore.DbSet1[Entities.Models.Product]' while attempting to activate 'Repositories.RepositoryContext'.) (Error while validating the service descriptor 'ServiceType: Repositories.Contracts.IProductRepository Lifetime: Scoped ImplementationType: Repositories.ProductRepository': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbSet1[Entities.Models.Product]’ while attempting to activate ‘Repositories.RepositoryContext’.)

InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbSet1[Entities.Models.Product]’ while attempting to activate ‘Repositories.RepositoryContext’.
`

I checked my repository layers one by one, I checked my Program.cs links one by one, I checked the instructions on microsoft’s site, but I guess I was not able to solve this with my current level of knowledge.

My repositorycontext page looks like this

public class RepositoryContext : DbContext
{
    public DbSet<Product> Products { get; set; } 
    public DbSet<Category> Categories { get; set; } 


    public RepositoryContext(DbContextOptions<RepositoryContext> options, DbSet<Product> products, DbSet<Category> categories) :
        base(options) 
    {
       
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder); 
        modelBuilder.Entity<Product>()
            .HasData(new Product() { Id = 1, ProductName = "Laptop", Price = 1000 },
                new Product() { Id = 2, ProductName = "Keyboard", Price = 500 },
                new Product() { Id = 3, ProductName = "Computer", Price = 2500 },
                new Product() { Id = 4, ProductName = "Monitor", Price = 1000 },
                new Product() { Id = 5, ProductName = "Deck", Price = 500 }
            ); 
        modelBuilder.Entity<Category>()
            .HasData(
                new Category() { CategoryId = 1, CategoryName = "Book" },
                new Category() { CategoryId = 2, CategoryName = "Electronic" });
    }
}

This is my code at the beginning of the program

var builder = WebApplication.CreateBuilder(args);
builder.Services
    .AddControllersWithViews(); 
builder.Services.AddDbContext<RepositoryContext>(options =>
{
    options.UseSqlite(builder.Configuration.GetConnectionString
        ("sqlconnection"), 
        b => b.MigrationsAssembly("StoreApp")); 
});
builder.Services.AddScoped<IRepositoryManager, RepositoryManager>();
builder.Services.AddScoped<IProductRepository, ProductRepository>();


var app = builder.Build();

app.UseStaticFiles(); 
app.UseHttpsRedirection(); 
app.UseRouting(); 


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

app.Run();

and the objects have this shape

public class Product
{
    public int Id { get; set; }
    public String? ProductName { get; set; } = String.Empty; 
    public decimal Price { get; set; }
}

    public class Category
    {
        public int CategoryId { get; set; }
        public String? CategoryName { get; set; }= String.Empty;
        
    }

2

Answers


  1. You should not inject DbSet‘s, just remove them from ctor:

    public class RepositoryContext : DbContext
    {
        public DbSet<Product> Products { get; set; } 
        public DbSet<Category> Categories { get; set; } 
    
    
        public RepositoryContext(DbContextOptions<RepositoryContext> options) :
            base(options) 
        {
           
        }
        ...
    }
    

    Or:

    public class RepositoryContext : DbContext
    {
        public DbSet<Product> Products => Set<Product>();
        public DbSet<Category> Categories => Set<Category>();
    
    
        public RepositoryContext(DbContextOptions<RepositoryContext> options) :
            base(options) 
        {
           
        }
        ...
    }
    

    To handle nullability warnings if any.

    See also:

    Login or Signup to reply.
  2. What need do you have to inject DbSet<Product> and DbSet<Category> into the constructor? Should work fine without those parameters in the constructor.

    Those two arguments could not be constructed and that’s what brought about the serivce resolution exception.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search