【问题标题】:Issue with Services when attempting to add Context to Startup.cs尝试将上下文添加到 Startup.cs 时出现服务问题
【发布时间】:2020-01-13 19:32:00
【问题描述】:

我在尝试迁移项目时收到此错误:

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-mvc entity-framework-core blazor blazor-server-side


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-11-04
      • 1970-01-01
      • 1970-01-01
      • 2019-05-07
      • 1970-01-01
      • 2020-11-08
      • 2019-10-12
      • 2015-06-12
      • 1970-01-01
      相关资源
      最近更新 更多