William
William

Reputation: 43

Dependency Injection - Multiple projects

I'm creating a wep api and this is the current structure:

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) 

For information I had everything on the same project and decided to split into multiple class libraries.
What I've done until now:

I think that my problem is related to dependency injection because when I try to access a controller from postman or from the browser this error happens:

InvalidOperationException: Error while validating the service descriptor 'ServiceType: FootballManager.REPO.ILeagueRepository Lifetime: Scoped ImplementationType: FootballManager.REPO.LeagueRepository': Unable to resolve service for type 'FootballManager.DAL.FootballManagerAPIContext' while attempting to activate 'FootballManager.REPO.LeagueRepository'.

My Startup.cs looks like this:

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();
            });
        }
    }
}

This is my controller code where I do the injection:

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();
        }
    }

For my DbContext connection I did directly on the DAL project like this (I dont think that the problem is here):

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;");
            }
        }
}

After hours on the web and stackoverflow I still can't find any working solution...
How can I solve this error and why I'm having this? Thank you.

Upvotes: 1

Views: 911

Answers (3)

riffnl
riffnl

Reputation: 3183

You never instantiate your DbContext - the error is very explicit about that;

Unable to resolve service for type 'FootballManager.DAL.FootballManagerAPIContext'

You also need to register the DbContext you need in the startup including configuration

Upvotes: 1

Liviu Mihaianu
Liviu Mihaianu

Reputation: 289

I think this will help you. Check out this video in which i explain how to implement dependency injection using autofac. https://studio.youtube.com/video/XvklkAj7qPg/edit

Also i sugest that you should use disposable database connection, connect and disconnect in every method. So do not use dependency injection for db context.

Check if you registered the db context. services.AddDbContext(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));

In the services configuration i can't see it.

Thanks, Liviu

Upvotes: 0

Dani Alderete
Dani Alderete

Reputation: 117

I cant add comments to you question so I leave this here:

Maybe its a stupid question but, maybe you forgot it:

Does LeagueRepository inherit from ILeagueRepository?

Upvotes: 0

Related Questions