依赖注入-多个项目

时间:2020-05-04 11:30:04

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

我正在创建一个wep api,这是当前结构:

API - The Web API  (.net core web api project)
DAL - DbContext and Entities  (.net core class library)
DTO - Data Transfert Objects - The classes I send to the client without sensible data (.net core class library) 
REPO - Contains de Interfaces and Repositories (.net core class library) 

有关信息,我将所有内容都放在同一个项目上,并决定拆分为多个类库。
到目前为止,我所做的事情:

  • 在每个项目之间添加了引用
  • 更新使用
  • 将名称空间名称更改为正确的名称
  • 解决方案为0个错误

我认为我的问题与依赖注入有关,因为当我尝试从邮递员或从浏览器访问控制器时,会发生此错误:

InvalidOperationException:验证服务描述符'ServiceType:FootballManager.REPO.ILeagueRepository时限:范围实现类型:FootballManager.REPO.LeagueRepository'时出错:尝试激活'FootballManager时无法解析'FootballManager.DAL.FootballManagerAPIContext'类型的服务.REPO.LeagueRepository”。

我的Startup.cs看起来像这样:

using FootballManager.REPO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace FootballManager.API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddCors(options =>
            {
                options.AddDefaultPolicy(
                    builder =>
                    {
                        builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
                    });
            });

            services.AddControllers().AddNewtonsoftJson(options =>
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
            );

            services.AddScoped<ILeagueRepository, LeagueRepository>();
            services.AddScoped<IMatchRepository, MatchRepository>();
            services.AddScoped<IPlayerRepository, PlayerRepository>();
            services.AddScoped<IRefereeRepository, RefereeRepository>();
            services.AddScoped<ITeamRepository, TeamRepository>();

        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseCors();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

这是我进行注入的控制器代码:

public class LeaguesController : ControllerBase
    {
        private readonly ILeagueRepository _repo;

        public LeaguesController(ILeagueRepository repo)
        {
            _repo = repo;
        }

        [HttpGet]
        public async Task<ActionResult<IEnumerable<LeagueDto>>> GetLeagues()
        {
            return await _repo.GetAll();
        }
    }

对于我的DbContext连接,我像这样直接在DAL项目上做过(我不认为问题出在这里):

public partial class FootballManagerAPIContext : DbContext
    {
        public FootballManagerAPIContext()
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer(@"Server =.\SQLEXPRESS; Database = FootballManagerAPI; Trusted_Connection = True;");
            }
        }
}

经过数小时的网络和stackoverflow,我仍然找不到任何有效的解决方案...
我该如何解决这个错误以及为什么会有这个错误?谢谢。

3 个答案:

答案 0 :(得分:1)

您永远不会实例化您的DbContext-该错误非常明显;

无法解析类型为'FootballManager.DAL.FootballManagerAPIContext'的服务

您还需要在启动时注册所需的DbContext,包括配置

答案 1 :(得分:0)

我认为这会对您有所帮助。 观看此视频,其中我解释了如何使用autofac实施依赖项注入。 https://laravel.com/docs/7.x/database#running-queries

我还建议您应使用一次性数据库连接,在每种方法中都应进行连接和断开连接。因此,请勿对数据库上下文使用依赖项注入。

检查是否注册了数据库上下文。 services.AddDbContext(options => options.UseSqlServer(Configuration [“ ConnectionStrings:DefaultConnection”])));

在服务配置中,我看不到它。

谢谢, Liviu

答案 2 :(得分:0)

我无法向您的问题添加评论,所以我将其保留在这里:

也许这是一个愚蠢的问题,但是,也许您忘记了它:

LeagueRepository是否继承自ILeagueRepository?