System.AggregateException выброшено - PullRequest
1 голос
/ 05 мая 2020

Я получаю следующую ошибку, когда пытаюсь выполнить свой код:

«Невозможно создать некоторые службы (Ошибка при проверке дескриптора службы ServiceType: RESTAPI. Models.IGebruikerRepository Lifetime: Scoped ImplementationType: RESTAPI.Data.Repositories.GebruikerRepository ': не удалось разрешить службу для типа' RESTAPI.Data.GebruikerContext 'при попытке активировать' RESTAPI.Data.Repositories.Gebruik *. *) 1005 *

В моем коде много классов, но я вставлю самые важные из них ниже:

Startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using NSwag;
using NSwag.Generation.Processors.Security;
using RESTAPI.Data;
using RESTAPI.Data.Repositories;
using RESTAPI.Models;

namespace RESTAPI
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddScoped<IGebruikerRepository, GebruikerRepository>();
            services.AddOpenApiDocument(c =>
            {
              c.DocumentName = "apidocs";
              c.Title = "PetConnectAPI";
              c.Version = "v1";
              c.Description = "The PetConnect API documentation description.";


            });

           services.AddCors(options => options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin()));

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseOpenApi();
            app.UseSwaggerUi3();


            app.UseHttpsRedirection();

            app.UseRouting();



            //app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseCors("AllowAllOrigins");



    }
   }
}

GebruikerContext.cs:

using System;
using Microsoft.EntityFrameworkCore;
using RESTAPI.Models;

namespace RESTAPI.Data
{
  public class GebruikerContext: DbContext
  {
    public GebruikerContext(DbContextOptions<GebruikerContext> options)
       : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {


      builder.Entity<Gebruiker>().Property(g => g.GebruikerId).IsRequired();
      builder.Entity<Gebruiker>().Property(g => g.Voornaam).IsRequired().HasMaxLength(50);
      builder.Entity<Gebruiker>().Property(g => g.Achternaam).IsRequired().HasMaxLength(50);
      builder.Entity<Gebruiker>().Property(g => g.Email).IsRequired().HasMaxLength(200);

      /*builder.Entity<Dier>().Property(d => d.Id).IsRequired();
      builder.Entity<Dier>().Property(d => d.Naam).IsRequired().HasMaxLength(30);
      builder.Entity<Dier>().Property(d => d.Soort).HasMaxLength(40);
      builder.Entity<Dier>().Property(d => d.Gebruiker).IsRequired();


      builder.Entity<Post>().Property(p => p.PostID).IsRequired();
      builder.Entity<Post>().Property(p => p.Datum).IsRequired();
      builder.Entity<Post>().Property(p => p.Dier).IsRequired();
      builder.Entity<Post>().Property(p => p.Tip).IsRequired().HasMaxLength(1000);

      builder.Entity<Comment>().Property(c => c.CommentID).IsRequired();
      builder.Entity<Comment>().Property(c => c.Inhoud).IsRequired().HasMaxLength(200);
      builder.Entity<Comment>().Property(c => c.gebruiker).IsRequired();
      builder.Entity<Comment>().Property(c => c.post).IsRequired();


      builder.Entity<Like>().Property(l => l.LikeID).IsRequired();
      builder.Entity<Like>().Property(l => l.post).IsRequired();*/
    }

    public DbSet<Gebruiker> Gebruikers{ get; set; }
    public DbSet<Dier> Dieren { get; set; }
    public DbSet<Post> Posts { get; set; }
    public DbSet<Like> Likes { get; set; }
    }
}

GebruikerController.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using RESTAPI.Data;
using RESTAPI.Data.Repositories;
using RESTAPI.DTOs;
using RESTAPI.Models;

namespace RESTAPI.Controllers
{
  [ApiConventionType(typeof(DefaultApiConventions))]
  [Produces("application/json")]
  [Route("api/[controller]")]
  public class GebruikersController : ControllerBase
  {
    private readonly IGebruikerRepository _gebruikerRepository;

    public GebruikersController(IGebruikerRepository context)
    {
            _gebruikerRepository = context;
    }

    // GET: api/values
    /// <summary>
    /// Geeft alle gebruikers geordend op achternaam
    /// </summary>
    /// <returns>array van gebruikers</returns>
    [HttpGet("/Gebruikers")]
    public String GetGebruikers()
    {
            //return _gebruikerRepository.GetAlleGebruikers().OrderBy(d => d.Achternaam);
            return "test";
    }

    // GET api/values/5
    /// <summary>
    /// Geeft de gebruiker met het gegeven id terug
    /// </summary>
    /// <param name="id">het id van de gebruiker</param>
    /// <returns>De gebruiker</returns>
    [HttpGet("{id}")]
    public ActionResult<Gebruiker> GetGebruiker(int id)
    {
      Gebruiker gebruiker = _gebruikerRepository.GetBy(id);
      if (gebruiker == null) return NotFound();
      return gebruiker;
    }

    // POST api/values
    /// <summary>
    /// Voegt een nieuwe gebruiker toe
    /// </summary>
    /// <param name="gebruiker">De nieuwe gebruiker</param>
    [HttpPost]
    public ActionResult<Gebruiker> PostGebruiker(GebruikerDTO gebruiker)
    {
      Gebruiker nieuweGebruiker = new Gebruiker(gebruiker.Voornaam, gebruiker.Achternaam);
      _gebruikerRepository.Add(nieuweGebruiker);
      _gebruikerRepository.SaveChanges();

      return CreatedAtAction(nameof(nieuweGebruiker), new { id = nieuweGebruiker.GebruikerId }, nieuweGebruiker);
    }

    // PUT api/values/5
    /// <summary>
    /// Wijzigt een gebruiker
    /// </summary>
    /// <param name="id">id van de gebruiker dat gewijzigd wordt</param>
    /// <param name="gebruiker">de gewijzigde gebruiker</param>
    [HttpPut("{id}")]
    public ActionResult PutGebruiker(int id, Gebruiker gebruiker)
    {
      if (id != gebruiker.GebruikerId)
      {
        return BadRequest();
      }
      _gebruikerRepository.Update(gebruiker);
      _gebruikerRepository.SaveChanges();
      return NoContent();
    }

    // DELETE api/values/5
    /// <summary>
    /// verwijdert een gebruiker
    /// </summary>
    /// <param name="id">id van de gebruiker dat verwijdert moet worden</param>
    [HttpDelete("{id}")]
    public IActionResult DeleteGebruiker(int id)
    {
      Gebruiker gebruiker = _gebruikerRepository.GetBy(id);
      if (gebruiker == null)
      {
        return NotFound();
      }
      _gebruikerRepository.Delete(gebruiker);
      _gebruikerRepository.SaveChanges();
      return NoContent();
    }
  }
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

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

GebruikerRepository.cs:

    using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using RESTAPI.Models;

namespace RESTAPI.Data.Repositories
{
  public class GebruikerRepository : IGebruikerRepository
  {
    private readonly GebruikerContext _context;
    private readonly DbSet<Gebruiker> _gebruikers;

    public GebruikerRepository(GebruikerContext dbcontext)
    {
      _context = dbcontext;
      _gebruikers = dbcontext.Gebruikers;
    }

    public void Add(Gebruiker gebruiker)
    {
      _gebruikers.Add(gebruiker);
    }

    public void Delete(Gebruiker gebruiker)
    {
      _gebruikers.Remove(gebruiker);
    }

    public IEnumerable<Gebruiker> GetAlleGebruikers()
    {
      return _gebruikers.Include(g => g.Dieren).ToList();
    }

    public Gebruiker GetBy(int id)
    {
      return _gebruikers.Include(g => g.Dieren).SingleOrDefault(r => r.GebruikerId == id);
    }

    public void SaveChanges()
    {
      _context.SaveChanges();
    }

    public void Update(Gebruiker gebruiker)
    {
      _context.Update(gebruiker);
    }
  }
}

Если кто-нибудь может мне помочь, спасибо! Я не могу понять.

1 Ответ

0 голосов
/ 05 мая 2020

GebruikerRepository имеет зависимость конструктора от GebruikerContext. Вы зарегистрировали первый (через его интерфейс) в коллекции сервисов, но не зарегистрировали второй. Вы можете зарегистрировать его с помощью AddScoped или AddTransient, как и другие типы, но проще зарегистрировать класс, производный от DbContext, с помощью AddDbContext, потому что он заботится об определенных значениях по умолчанию.

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();


    // Add this line:
    services.AddDbContext<GebruikerContext>();


    services.AddScoped<IGebruikerRepository, GebruikerRepository>();
    services.AddOpenApiDocument(c =>
    {
        c.DocumentName = "apidocs";
        c.Title = "PetConnectAPI";
        c.Version = "v1";
        c.Description = "The PetConnect API documentation description.";
    });

    services.AddCors(options => options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin()));
}

Где внутри метода, который вы добавляете, эта строка на самом деле не важна. Возможно, вам потребуется передать лямбда-выражение конфигурации и / или ServiceLifetime для ваших конкретных требований c. Дополнительную информацию см. В документации .

Совет: вы, скорее всего, снова столкнетесь с этим исключением, если не через неделю, то, может быть, через год. Обратите внимание на то, как он читается, как это соотносится с задействованными типами и как вы его разрешили. Вы поблагодарите себя в следующий раз, когда увидите это.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...