我有一个 ASP.NET Core Web 应用程序,我在其中添加了
DbContext
:
string connectionString = builder.Configuration
.GetConnectionString("DefaultConnection")
?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<HomeNotificationsDbContext>(options => options.UseSqlServer(connectionString));
builder.Services.AddHomeNotificationApplicationServices(typeof(IUserService));
AddHomeNotificationApplicationServices
方法是一种扩展方法,它通过反射将我的所有服务注册为作用域。启动得很好。但每当我尝试与 Web API 一起启动它并使用相同的方法注册相同的服务时,我都会收到以下错误:
尝试激活“HomeNotifications.Services.Data.HomeAuthenticationService”时无法解析类型“HomeNotifications.Data.HomeNotificationsDbContext”的服务。
HomeAuthenticationService
使用依赖注入创建DbContext
的只读实例:
public class HomeAuthenticationService : IHomeAuthenticationService
{
private readonly HomeNotificationsDbContext dbContext;
public HomeAuthenticationService(HomeNotificationsDbContext dbContext)
{
this.dbContext = dbContext;
}
// ...
}
我尝试将
DbContext
添加为 API 中的范围服务,因为我无权访问那里的 Web 应用程序的配置设置,但这没有成功。我可以将连接字符串添加到 API 配置文件中,但我不确定这是否是正确的方法,因为我是一个相当新的开发人员。任何提示将不胜感激。
我尝试将 DbContext 添加为 API 中的范围服务,因为我 无权访问那里的网络应用程序的配置设置, 但这并没有成功。我可以将连接字符串添加到 API 配置文件,
嗯,根据您的情况和描述,我已经厌倦了调查您的问题,并且无法重现您遇到的错误。
我的测试最好,我认为你应该检查几件事。
首先,如果您的 dbContext 项目驻留在不同的项目中,请确保您已在主项目中添加了引用。因为错误提示,DI没有相应注入。
另一个重要的事情是你的项目结构。我不知道是怎么回事。但我尝试过以下项目结构,它的工作没有任何错误,并且我能够从数据库中提取值。
分享一下,我有多累:
DbContext 类:
using DbContextTestApp.Models;
using Microsoft.EntityFrameworkCore;
namespace DbContextTestApp.Data
{
public class HomeNotificationsDbContext: DbContext
{
public HomeNotificationsDbContext(DbContextOptions<HomeNotificationsDbContext> options)
: base(options)
{
}
public DbSet<Employee> Employees { get; set; }
}
}
控制器类:
using DbContextTestApp.Data;
using DbContextTestApp.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
namespace DbContextTestApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly HomeNotificationsDbContext _context;
public HomeController(ILogger<HomeController> logger, HomeNotificationsDbContext context)
{
_logger = logger;
_context = context;
}
public IActionResult Index()
{
var employees = _context.Employees;
return View();
}
}
}
注意: Web API 项目在添加 DbContext 类时没有差异。
程序.cs:
using DbContextTestApp.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<HomeNotificationsDbContext>(options =>
options.UseSqlServer(connectionString));
// Add services to the container.
builder.Services.AddControllersWithViews();
输出: