在 ASP.NET Core Web API 中验证服务描述符时,某些服务无法构造错误

问题描述 投票:0回答:1

我正在使用实体框架构建一个简单的 ASP.NET Core Web API。但是在尝试运行应用程序时出现此错误:

某些服务无法构建(验证服务描述符时出错)

我的代码如下 -

DbContext
:

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions options) : base(options)
    {
    }

    public DbSet<Product> Products { get; set; }
}

DbContext
工厂:

public class ApplicationDbContextFactory : IDbContextFactory<ApplicationDbContext>
{
    private readonly DbContextOptions _options;

    public ApplicationDbContextFactory(DbContextOptions options)
    {
        _options = options;
    }

    public ApplicationDbContext CreateDbContext()
    {
        return new ApplicationDbContext(_options);
    }
}

其中一项服务

public class ProductService : IProductService
{
    private readonly ApplicationDbContextFactory _contextFactory;

    public ProductService(ApplicationDbContextFactory contextFactory)
    {
        _contextFactory = contextFactory;
    }

    public async Task<IEnumerable<Product>> GetAllAsync()
    {
        using (ApplicationDbContext context = _contextFactory.CreateDbContext())
        {
            IEnumerable<Product> products = await context.Products.ToListAsync();
            return products.Select(p => new Product() { Id = p.Id, ProductName = p.ProductName, Price = p.Price, Qty = p.Qty });
        }
    }
}

我的依赖注入设置:

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString), optionsLifetime: ServiceLifetime.Singleton);
builder.Services.AddDbContextFactory<ApplicationDbContext>(options => options.UseSqlServer(connectionString));
builder.Services.AddTransient<IProductService, ProductService>();
c# entity-framework asp.net-core dependency-injection
1个回答
0
投票

您的代码存在一些问题。

首先,你从来没有真正注册你的工厂实现类。因此,您只需使用 DbContextFactory 的默认实现即可。 将启动/程序文件更改为如下所示:

 builder.Services.AddDbContextFactory<ApplicationDbContext, ApplicationDbContextFactory>(options =>
{
    options.UseSqlServer(connectionString);
});

那么你的ProductService需要注入接口。像这样的东西:

public class ProductService
{
    private readonly IDbContextFactory<ApplicationDbContext> _contextFactory;

    public ProductService(IDbContextFactory<ApplicationDbContext> contextFactory)
    {
        _contextFactory = contextFactory;
    }

    public async Task<IEnumerable<Product>> GetAllAsync()
    {
        using (ApplicationDbContext context = _contextFactory.CreateDbContext())
        {
            IEnumerable<Product> products = await context.Products.ToListAsync();
            return products.Select(p => new Product() { Id = p.Id, ProductName = p.ProductName, Price = p.Price, Qty = p.Qty });
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.