c# - 尝试在 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);
}
}
}
解决方案
异常中显示的命名空间与显示的示例代码不同。项目中可能存在冲突的类型(未显示)。
如果确实如此,则在向容器注册类型时包含完整的命名空间以避免冲突。
根据显示的代码,那将是
services.AddScoped<IProjects, ApexServices.ProjectService>();
推荐阅读
- mysql - 如何在 mySQL 工作台中创建函数
- node.js - 有没有在node js的socket程序中连接客户端和服务器的解决方案
- groovy - Groovy - 循环通过 JSON 对象并将值填充为单行
- spring-boot - Spring Boot中应用属性优先级顺序的观察
- python-3.x - 如何在自定义函数中使用字典从大型数据框中计算新列?
- c# - 字典/列表对象的 C# 多态 JSON 反序列化
- mysql - Spring boot 和 ProxySQL 一起用,有用吗?
- selenium-chromedriver - WebdriverIO chromedriver 首选项被忽略
- android - 关闭活动时重新初始化片段
- sql-server - SQL Server 管理工作室 v18.8