【发布时间】:2020-08-20 12:33:31
【问题描述】:
我在尝试执行代码时遇到以下错误:
"某些服务无法构建(验证时出错 服务描述符'ServiceType: RESTAPI.Models.IGebruikerRepository 生命周期:范围 实施类型:RESTAPI.Data.Repositories.GebruikerRepository': 无法解析“RESTAPI.Data.GebruikerContext”类型的服务 在尝试激活时 'RESTAPI.Data.Repositories.GebruikerRepository'.)"
我的代码有很多类,但我将在下面粘贴最重要的类:
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();
}
}
}
程序.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);
}
}
}
如果有人可以帮助我,谢谢! 我想不通。
【问题讨论】:
-
向我们展示
GebruikerRepository类 -
@Jasen 补充感谢您的回复
-
您似乎尚未将
GebruikerContext添加到服务集合中。通常这是通过在ConfigureServices中调用services.AddDbContext来完成的。 -
解决了这个问题,你能把它写成一个帖子,这样我就可以投票并标记为答案!
标签: c# asp.net-core