【问题标题】:.NET Core dependency injection error : "Unable to resolve service for type 'AspNetCoreWebAPI.Data.IBookRepository'".NET Core 依赖注入错误:“无法解析“AspNetCoreWebAPI.Data.IBookRepository”类型的服务”
【发布时间】:2021-12-30 11:46:44
【问题描述】:

我正在尝试在 VS Code 中使用 ADO.NET 来学习 ASP.NET Core Web API,结果我遇到了一个我不理解的错误。

在startup 中,我添加了两个作用域服务:

using System.Net;
using AspNetCoreWebAPI.Data;
using Microsoft.AspNetCore.Diagnostics;
using AspNetCoreWebAPI.Helpers;

namespace AspNetCoreWebAPI
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<IAuthRepository, AuthRepository>();
            services.AddScoped<IBookRepository, BookRepository>();           
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();
            app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
            app.UseAuthentication();
            app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
        }
    }
}

这是我的BooksController:

public class BooksController : ControllerBase
{
    private readonly IBookRepository _repo;

    public BooksController(IBookRepository repo)
    {
        _repo = repo;
    } 

    [HttpGet]
    public async Task<IActionResult> Get()
    {
        MyBooks = await _repo.GetBooks();
        return Ok(MyBooks);
    }
}

程序员.cs

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": ".NET Core Launch (web)",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "build",
            "program": "${workspaceFolder}/bin/Debug/net6.0/webapi2.dll",
            "args": [],
            "cwd": "${workspaceFolder}",
            "stopAtEntry": false,
            "serverReadyAction": {
                "action": "openExternally",
                "pattern": "\\bNow listening on:\\s+(https?://\\S+)",
                "uriFormat": "%s/weatherforecast"
            },
            "env": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            },
            "sourceFileMap": {
                "/Views": "${workspaceFolder}/Views"
            }
        },
        {
            "name": ".NET Core Attach",
            "type": "coreclr",
            "request": "attach"
        }
    ]
}

tasks.json

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "command": "dotnet",
            "type": "process",
            "args": [
                "build",
                "${workspaceFolder}/webapi2.csproj",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "problemMatcher": "$msCompile"
        },
        {
            "label": "publish",
            "command": "dotnet",
            "type": "process",
            "args": [
                "publish",
                "${workspaceFolder}/webapi2.csproj",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "problemMatcher": "$msCompile"
        },
        {
            "label": "watch",
            "command": "dotnet",
            "type": "process",
            "args": [
                "watch",
                "run",
                "${workspaceFolder}/webapi2.csproj",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "problemMatcher": "$msCompile"
        }
    ]
}

Ibook 存储库

public interface IBookRepository
    {
           Task<List<Books>> GetBooks();
    }

书库

public class BookRepository:IBookRepository
    {
        public async Task<List<Books>> GetBooks()
        {
            List<Books> MyBooks = new List<Books>();

            DataConnection dc = new DataConnection();
            var task = new Task(() =>
            {
                DataTable dt = dc.GetData("SELECT * FROM dbo.Books");

                // POPULATE THE LIST WITH DATA.
                foreach (DataRow dr in dt.Rows)
                {
                    MyBooks.Add(new Books
                    {
                        BookID = Convert.ToInt32(dr["BookID"]),
                        BookName = dr["BookName"].ToString(),
                        Category = dr["Category"].ToString(),
                        Price = Convert.ToDecimal(dr["Price"])
                    });
                }
            });
            task.Start();
            await task;
            return MyBooks;

        }
        
    }

每当我在 BooksController 上调用方法时,都会收到此错误:

InvalidOperationException:尝试激活“AspNetCoreWebAPI.Controllers.BooksController”时无法解析“AspNetCoreWebAPI.Data.IBookRepository”类型的服务

【问题讨论】:

  • 您好,错误消息指出您的应用程序正在尝试创建BooksController 的实例,但它不知道如何创建IBookRepository 的实例以传递给构造函数。但是从你分享的代码来看,你的依赖注入没有问题。你能提供整个startup.cs吗?
  • Hi Xinran Shen 感谢您的评论我已经编辑了添加完整startup.cs的问题
  • 您好,我从您分享的代码中没有发现依赖注入有任何错误,我猜您代码中的某些设置可能会影响依赖注入,如果您愿意,可以分享您的整个项目。对了,为什么startup里没有services.AddControllers()?
  • 你的代码没问题。这是您的依赖注入中的一个问题。你能分享你的存储库接口和实现吗?
  • 你好,你用的是哪个版本的.net?programer.cs中的代码是.net 6的风格,但是.net 6没有Startup,我很困惑关于这个

标签: c# visual-studio-code .net-core dependency-injection asp.net-core-webapi


【解决方案1】:

您可以在programer.cs 中添加此代码:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddScoped<IBookRepository, BookRepository>();
//.......

【讨论】:

猜你喜欢
  • 2017-04-15
  • 1970-01-01
  • 2022-12-20
  • 2021-10-29
  • 1970-01-01
相关资源
最近更新 更多