【发布时间】:2020-04-22 23:56:15
【问题描述】:
花了太多时间试图弄清楚这一点。谢谢你的帮助。 .Net Core 3.1 尝试在 Startup.cs 中注册服务
错误 CS0311:类型“Apex.UI.MVC.ProjectService”不能用作泛型类型或方法
ServiceCollectionServiceExtensions.AddScoped<TService, TImplementation>(IServiceCollection)中的类型参数“TImplementation”。没有从“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);
}
}
}
【问题讨论】:
-
好吧,它说
Apex.UI.MVC.ProjectService不要实现Apex.EF.Data.IProjects。那么Apex.UI.MVC.ProjectService注册的类型正确吗? -
您的
ProjectService在命名空间之外声明。 -
您的代码中是否有另一个
ProjectService实现——特别是在Apex.UI.MVC命名空间中?您在问题中显示的那个不会在错误中报告为属于该名称空间,因为它位于全局名称空间中。如果您使用的是 Visual Studio,请在AddScoped行中的ProjectService上右键客户端并单击Go To Implementation- 它会导航到导致错误的类(提示:它与您在你的问题)。 -
好的,我编辑了帖子,我正在测试的一些错误的东西留在了那里。 ProjectService 在解决方案“ApexServices”中的不同项目中实现。我有对数据的引用,并且以不同的方式来回引用。就像 Startup 看不到我的 Apex 服务层一样。
-
@user1895831 异常中显示的命名空间与显示的示例代码不同。项目中可能存在冲突的类型(未显示)。如果没有 minimal reproducible example 澄清您的具体问题或其他详细信息以准确突出所做的工作,将很难重现问题以更好地理解实际 问题。
标签: c# asp.net-core dependency-injection asp.net-core-mvc