首页 > 解决方案 > 尝试将上下文添加到 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 中寻求帮助,但他们似乎也不知道为什么。

标签: c#asp.net-core-mvcentity-framework-coreblazorblazor-server-side

解决方案


事实证明,我的 Context 的构造函数被设置为 Protected 而不是 Public。问题解决了。谢谢阅读。


推荐阅读