ASP. NET Ошибка внедрения основной зависимости - невозможно разрешить службу для типа «Репозиторий» при попытке активировать «Службу» - PullRequest
0 голосов
/ 26 апреля 2020

Я пытаюсь создать базовое приложение ASP. NET, используя общий шаблон репозитория c, используя Entity Framework вместе со слоем сервиса. Однако всякий раз, когда я запускаю свой проект, я получаю сообщение об ошибке:

Не удается разрешить службу для типа 'GameSource.Data.Repositories. GameRepository ' при попытке активировать ' GameSource.Services. GameService '.

Unable to resolve service for type GameRepository while attempting to activate GameService

GamesController.cs :

    public class GamesController : Controller
    {
        private IGameService gameService;

        public GamesController(IGameService gameService)
        {
            this.gameService = gameService;
        }
    }

GameService.cs:

    public class GameService : IGameService
    {
        private GameRepository gameRepo;

        public GameService(GameRepository gameRepo)
        {
            this.gameRepo = gameRepo;
        }
    }

GameRepository.cs:

    public class GameRepository : BaseRepository<Game>, IGameRepository
    {
        private GameSource_DBContext context;
        private DbSet<Game> gameEntity;

        public GameRepository(GameSource_DBContext context) : base(context)
        {
            this.context = context;
            gameEntity = context.Set<Game>();
        }
     }

BaseRepository.cs :

    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private GameSource_DBContext context;
        private DbSet<T> entity;

        public BaseRepository(GameSource_DBContext context)
        {
            this.context = context;
            entity = context.Set<T>();
        }
    }

GameSource_DBContext.cs:

    public class GameSource_DBContext : DbContext
    {
        public GameSource_DBContext(DbContextOptions<GameSource_DBContext> options) : base(options)
        {
        }

        public DbSet<Game> Game { get; set; }
        public DbSet<Genre> Genre { get; set; }
        public DbSet<Developer> Developer { get; set; }
        public DbSet<Publisher> Publisher { get; set; }
        public DbSet<Platform> Platform { get; set; }
    }

Startup.cs:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews().AddRazorRuntimeCompilation();

            services.AddDbContext<GameSource_DBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("GameSource_DB")));

            services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            services.AddScoped<IGameRepository, GameRepository>();
            services.AddScoped<IGameService, GameService>(); //Can't resolve service?
        }

Как вы можете видеть при запуске, я пытаюсь внедрить мой сервис, а также свой репозиторий, но он не может разрешить сервис для GameRepository при попытке активировать GameService. Я что-то пропустил? Является ли это правильным подходом для использования с Entity Framework, например, уровни repo + service?

Спасибо за ваше терпение.

1 Ответ

1 голос
/ 26 апреля 2020

В GameService измените его, чтобы он использовал интерфейс IGameRepository следующим образом:

public class GameService : IGameService
{
    private IGameRepository gameRepo;

    public GameService(IGameRepository gameRepo)
    {
        this.gameRepo = gameRepo;
    }
}

К вашему сведению, GameRepository не может быть разрешена, поскольку вы настроили внедрение зависимостей для внедрения хранилища, когда интерфейс IGameRepository используется в конструкторе, а не в конкретной реализации.

...