c# - 尝试将上下文添加到 Startup.cs 时出现服务问题
问题描述
尝试迁移项目时出现此错误:
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: AIR.Data.AmaxContext Lifetime: Scoped ImplementationType: AIR.Data.AmaxContext': A suitable constructor for type 'AIR.Data.AmaxContext' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.) (Error while validating the service descriptor 'ServiceType: AIR.Data.Services.SkuService Lifetime: Scoped ImplementationType: AIR.Data.Services.SkuService': A suitable constructor for type 'AIR.Data.AmaxContext' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.)
Unable to create an object of type 'AmaxContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
这是我的配置服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
var builder = new MySqlConnectionStringBuilder(
Configuration.GetConnectionString("AmaxContext")) {Password = Configuration["DbPassword"]};
var connection = builder.ConnectionString;
services.AddDbContext<AmaxContext>(options =>
options.UseMySql(connection, builder =>
{
builder.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null);
}));
services.AddScoped<SkuService>();
}
这是我的 skuservice:
using AIR.Data.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AIR.Data.Services
{
public class SkuService
{
private AmaxContext _context;
public SkuService(AmaxContext context)
{
_context = context;
}
public async Task<List<Core.SKU>> GetSkus()
{
return await _context.SKUs.ToListAsync();
}
}
}
我对 blazor 还是很陌生,我正在尝试从 mvc .net 核心迁移。我试图在 C# discord 和 Blazor discord 中寻求帮助,但他们似乎也不知道为什么。
解决方案
事实证明,我的 Context 的构造函数被设置为 Protected 而不是 Public。问题解决了。谢谢阅读。
推荐阅读
- python - 使用 python open-cv 分割报纸文章
- vue.js - 访问元素属性时Vue $refs未定义
- r - 不能对可能存在的列进行子集化
- c++ - 持续“错误 C2220:以下警告被视为错误”
- javascript - 为什么在 JS 函数调用完成后应用样式?
- angularjs - 带有异步管道的 Angular *ngfor 在 api 发布请求后不会更新 DOM
- nginx - nginx - 完全不区分大小写的 URL 匹配和文件查找
- c# - Fody PropertyChanged Weaver 导致内存问题
- reactjs - AWS S3:CORS 配置未实施
- powerbi - PowerBI 连接表和计算