首页 > 解决方案 > 尝试在 startup.cs 中激活服务时无法解析服务类型

问题描述

花了太多时间试图弄清楚这一点。谢谢你的帮助。.Net Core 3.1 尝试在 Startup.cs 中注册服务

错误 CS0311:类型“Apex.UI.MVC.ProjectService”不能用作泛型类型或方法中的类型参数“TImplementation” ServiceCollectionServiceExtensions.AddScoped<TService, TImplementation>(IServiceCollection)。没有从“Apex.UI.MVC.ProjectService”到“Apex.EF.Data.IProjects”的隐式引用转换。(CS0311) (Apex.UI.MVC)

services.AddScoped<IProjects, ProjectService>();
using System;
using Apex.EF.Data;
using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;
using System.Linq;
using Apex.UI.MVC.Models.Projects;

namespace Apex.UI.MVC.Controllers
{
    public class ProjectController : Controller
    {
        private IProjects _projects;
        public ProjectController(IProjects projects)
        {
            _projects = projects;
        }

        public IActionResult Index()
        {
            var projectModels = _projects.GetAll();

            var listingResult = projectModels
            .Select(result => new ProjectIndexListingModel
            {
                Id = result.Id,
                ProjectName = result.ProjectName,
                ProjectImage = result.ProjectImage

            });

            var model = new ProjectIndexModel()
            {
                Project = listingResult
            };
            return View(model);
        }

    }
}
using System;
using System.Collections.Generic;
using Apex.EF.Data;
using Apex.EF.Data.Models;

namespace Apex.EF.Data
{
    public interface IProjects
    {
        IEnumerable<Project> GetAll();
        Project GetById(int id);
        void Add(Project newProject);
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using Apex.EF.Data;
using Apex.EF.Data.Models;
using Microsoft.EntityFrameworkCore;

namespace ApexServices
{
    public class ProjectService : IProjects
    {
        private ApexContext _context;
        public ProjectService(ApexContext context)
        {
            _context = context;
        }

        public void Add(Project newProject)
        {
            _context.Add(newProject);
            _context.SaveChanges();
        }

        public IEnumerable<Project> GetAll()
        {
            return _context.Projects
                   .Include(project => project.Status.IsInShop == true);
        }

        public Project GetById(int id)
        {
            return _context.Projects
                .Include(project => project.Status.IsInShop==true)
                .FirstOrDefault(project => project.Id == id);

        }
    }
}

标签: c#asp.net-coredependency-injectionasp.net-core-mvc

解决方案


异常中显示的命名空间与显示的示例代码不同。项目中可能存在冲突的类型(未显示)。

如果确实如此,则在向容器注册类型时包含完整的命名空间以避免冲突。

根据显示的代码,那将是

services.AddScoped<IProjects, ApexServices.ProjectService>();

推荐阅读