我试图创建一个基本的asp.net core web api
的CRUD操作与实体框架,但我得到以下错误:
InvalidOperationException:尝试激活“Corewebapi.Controllers. LibrariesController”时,无法解析类型“Corewebapi.Models.MyDatabaseContext”的服务。和System.AggregateException:'无法构造某些服务(验证服务描述符时出错'ServiceType:Corewebapi.Controllers.LibrariesController Lifetime: transient 实现类型:Corewebapi.Controllers. LibrariesController':尝试激活“Corewebapi.Controllers. LibrariesController”时,无法解析类型“Corewebapi.Models.MyDatabaseContext”的服务。)
我的代码是
using System;
using System.Collections.Generic;
namespace Corewebapi.Models
{
public partial class Library
{
public int Bookid { get; set; }
public string Bookname { get; set; }
public int? Price { get; set; }
public DateTime? Date { get; set; }
public string Author { get; set; }
}
}
字符串
对于db上下文
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace Corewebapi.Models
{
public partial class MyDatabaseContext : DbContext
{
public MyDatabaseContext()
{
}
public MyDatabaseContext(DbContextOptions<MyDatabaseContext> options)
: base(options)
{
}
public virtual DbSet<Library> Library { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("Server=localhost;Database=MyDatabase;Trusted_Connection=True;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Library>(entity =>
{
entity.HasKey(e => e.Bookid);
entity.Property(e => e.Bookid).HasColumnName("bookid");
entity.Property(e => e.Author)
.HasColumnName("author")
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.Bookname)
.HasColumnName("bookname")
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.Date)
.HasColumnName("date")
.HasColumnType("date");
entity.Property(e => e.Price).HasColumnName("price");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
型
对于控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Corewebapi.Models;
namespace Corewebapi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class LibrariesController : ControllerBase
{
private readonly MyDatabaseContext _context;
public LibrariesController(MyDatabaseContext context)
{
_context = context;
}
// GET: api/Libraries
[HttpGet]
public async Task<ActionResult<IEnumerable<Library>>> GetLibrary()
{
return await _context.Library.ToListAsync();
}
// GET: api/Libraries/5
[HttpGet("{id}")]
public async Task<ActionResult<Library>> GetLibrary(int id)
{
var library = await _context.Library.FindAsync(id);
if (library == null)
{
return NotFound();
}
return library;
}
// PUT: api/Libraries/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
[HttpPut("{id}")]
public async Task<IActionResult> PutLibrary(int id, Library library)
{
if (id != library.Bookid)
{
return BadRequest();
}
_context.Entry(library).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!LibraryExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Libraries
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
[HttpPost]
public async Task<ActionResult<Library>> PostLibrary(Library library)
{
_context.Library.Add(library);
await _context.SaveChangesAsync();
return CreatedAtAction("GetLibrary", new { id = library.Bookid }, library);
}
// DELETE: api/Libraries/5
[HttpDelete("{id}")]
public async Task<ActionResult<Library>> DeleteLibrary(int id)
{
var library = await _context.Library.FindAsync(id);
if (library == null)
{
return NotFound();
}
_context.Library.Remove(library);
await _context.SaveChangesAsync();
return library;
}
private bool LibraryExists(int id)
{
return _context.Library.Any(e => e.Bookid == id);
}
}
}
型
对于staratup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Corewebapi.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Corewebapi
{
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.AddConnections();
// services.AddDbContext<MyDatabaseContext>(options =>
// options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc()
.AddControllersAsServices();
services.AddControllers().AddControllersAsServices();
}
// 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.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
型
2条答案
按热度按时间0vvn1miw1#
只需确保在启动时包含您期望从DI容器中获得的类型,例如:以InboundMessageDTO类型为例。当您期望从DI接收InboundMessageDTO的示例时,必须按如下方式配置它:public void run();
当你希望有一个它的集合时,你可以按如下方式配置它:services.AddScoped();然后在构造器中执行以下操作:
private readonly List inboungMessagesDTO; private readonly InboundMessageDTO inboundMessage;
字符串
a7qyws3x2#
非常感谢那些试图帮助我的人,我通过添加这些行来解决这个问题
startup.cs
字符串