Home > database >  Some services are not able to be constructed in .net core 5.0
Some services are not able to be constructed in .net core 5.0

Time:05-25

I am working with .net core 5.0 with code first approach

I am working crud operation on product and category I inject the both service in startup.cs class but still get an below error :

'Some services are not able to be constructed (Error while validating the service descriptor 
'ServiceType: CrudDemo.Services.IService`2[CrudDemo.Models.Category,System.Int32] Lifetime: Scoped ImplementationType: 
CrudDemo.Services.CategoryService': Unable to resolve service for type 'CrudDemo.Models.AmazonDbContext' while attempting to activate 
'CrudDemo.Services.CategoryService'.) (Error while validating the service descriptor 'ServiceType: 
CrudDemo.Services.IService`2[CrudDemo.Models.Product,System.Int32] Lifetime: Scoped ImplementationType: CrudDemo.Services.ProductService': 
Unable to resolve service for type 'CrudDemo.Models.AmazonDbContext' while attempting to activate 'CrudDemo.Services.ProductService'.)'

startup.cs

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("AppConnectionString"));
            });

            services.AddControllersWithViews();
            services.AddScoped<IService<Category,int>, CategoryService>();
            services.AddScoped<IService<Product, int>, ProductService>();
        }

appsetting.json

"ConnectionStrings": {
    "AppConnectionString": "Data Source=localhost,Initial Catalog=databasename;User Id=**;Password=************"
  }

ApplicationDbContext.cs

    public class ApplicationDbContext: IdentityDbContext
    { 
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options)
        {
        }
    }

Iservice.cs

    public interface IService<TEntity, in TPk> where TEntity : class
    {
        Task<IEnumerable<TEntity>> GetAsync();
        Task<TEntity> GetAsync(TPk id);
        Task<TEntity> CreateAsync(TEntity entity);
    }

DepartmentController.cs

    public class DepartmentController : Controller
    {
        private readonly IService<Category, int> catServ;

        public DepartmentController(IService<Category, int> serv)
        {
            catServ = serv;
        }

AmazonDbContext.cs

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

        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Data Source=localhost;Initial Catalog=*****;User Id=*********;Password=***********");
        }
    }

CategoryService.cs

    public class CategoryService : IService<Category,int>
    {
        private readonly AmazonDbContext ctx;
        public CategoryService(AmazonDbContext ctx)
        {
            this.ctx = ctx;
        }

        public async Task<Category> CreateAsync(Category cat)
        {
            try
            {
                var res = await ctx.Categories.AddAsync(cat);
                await ctx.SaveChangesAsync();
                return res.Entity;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public async Task<IEnumerable<Category>> GetAsync()
        {
            return await ctx.Categories.ToListAsync();
        }

        public async Task<Category> GetAsync(int id)
        {
            return await ctx.Categories.FindAsync(id);
        }

need help

CodePudding user response:

Is it a type in your question CrudDemo.Models.AmazonDbContext? AmazonDbContext instead of ApplicationDbContext ?

public void ConfigureServices(IServiceCollection services)
    {
                              Application not Amazon
                              |                  |
                              v                  v  
        services.AddDbContext<ApplicationDbContext>(options => 
        {
...
        });

CodePudding user response:

You should register AmazonDbContext in ConfigureServices, but before that, as your commented error said, you must add a constructor that receives a parameter of type DbContextOptions<AmazonDbContext> into your AmazonDbContext class :

 public AmazonDbContext(DbContextOptions<AmazonDbContext> options)
        : base(options)
    { }

then register it:

 services.AddDbContext<AmazonDbContext>(options => { 
...
});

OR if for any reason you don't want your constructor have any parameter of DbContextOptions type, register your AmazonDbContext class like below:

services.AddDbContext<AmazonDbContext>();
  • Related