我正在用ASP开发一个Web API。净核心。当我使用post请求执行API时,在UnitController的post方法的断点之前会引发异常。
例外
请求启动HTTP/1.1 POSThttp://localhost:5000/api/unit应用程序/json 31失败:Microsoft. AspNetCore. Server. Kestrel[13]连接ID"0HKVTL9A1LTD4":应用程序抛出未处理的异常。系统。无效操作异常:在尝试激活“项目”时无法解析类型为“项目”的服务。DataAccess。存储库。UnitRepository'。
上下文
namespace Project.DataAccess.Library.Interface {
public interface IBaseRepository<M> where M : class, IEntity
{
IEnumerable<M> SelectAll();
M SelectByID(int id);
void Insert(M obj);
void Update(M obj);
void Delete(int id);
void Save();
}
}
namespace Project.DataAccess.Library {
public abstract class BaseRepository<M> : IBaseRepository<M> where M : class, IEntity
{
protected ProjectContext Db { get; }
private DbSet<M> table = null;
protected DbSet<M> Table
{
get
{
return this.table;
}
}
public BaseRepository(ProjectContext dbContext)
{
Db = dbContext;
this.table = Db.Set<M>();
}
public void Delete(int id)
{
M existing = this.SelectByID(id);
if (existing != null)
this.table.Remove(existing);
}
// others methods
}
}
namespace Project.DataAccess.Repository
{
public class UnitRepository : BaseRepository<Unit>, IUnitRepository
{
public UnitRepository(Projectcontext) : base(context) { }
}
}
namespace Project.Service
{
public class UnitService : BaseService<Unit>, IUnitService
{
public UnitService(UnitRepository unitRepository) : base(unitRepository) { }
}
}
namespace AssoManager.Service.Library
{
public abstract class BaseService<M> : IBaseService<M> where M : class, IEntity
{
private IBaseRepository<M> _repository;
public BaseService(IBaseRepository<M> repository)
{
_repository = repository;
}
public IEnumerable<M> GetAll()
{
return this._repository.SelectAll();
}
}
}
namespace Project
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
this.DataAccessMySqlConfiguration(services);
this.ConfigureRepository(services);
this.ConfigureServicesUnit(services);
this.ConfigureServicesUser(services);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
}
#region Database configuration
public void DataAccessMySqlConfiguration(IServiceCollection services)
{
services.AddDbContext<ProjectContext>(options => options.UseMySQL(Configuration.GetConnectionString("MsSQLConnection")));
}
#endregion
#region DataAccess configuration
public void ConfigureRepository(IServiceCollection services)
{
services.AddScoped<IUnitRepository, UnitRepository>();
services.AddScoped<IUserRepository, UserRepository>();
}
#endregion
#region Services configuration
/// <summary>
/// Is used to add unit services to the container
/// </summary>
public void ConfigureServicesUnit(IServiceCollection services)
{
services.AddTransient<IUnitService, UnitService>();
services.AddTransient<IMeetingService, MeetingService>();
}
/// <summary>
/// Is used to add user services to the container
/// </summary>
public void ConfigureServicesUser(IServiceCollection services)
{
services.AddTransient<IUserService, UserService>();
}
#endregion Services configuration
}
}
namespace Project.Controllers
{
[Route("api/[controller]")]
public class UnitController : Controller
{
private IUnitService UnitService;
public UnitController(IUnitService unitService)
{
UnitService = unitService;
}
// GET api/units
[HttpGet]
public IEnumerable<Unit> Get()
{
return UnitService.GetAll();
}
// GET api/unit/5
[HttpGet("{id}")]
public IActionResult Get(int id)
{
Unit unit;
//->Check
if (id < 1)
return BadRequest();
//->Processing
unit = UnitService.GetByID(id);
if (unit == null)
return NotFound();
return new ObjectResult(unit);
}
// POST api/unit
[HttpPost]
public IActionResult Post([FromBody]Unit unit)
{
//->Check
if (unit == null)
return BadRequest();
//->Processing
UnitService.Create(unit);
return CreatedAtRoute("Get", new { id = unit.Id }, unit);
}
// PUT api/unit/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/unit/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
版本
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.0.0",
"type": "platform"
},
"Microsoft.AspNetCore.Mvc": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
"Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.Logging": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.Extensions.Logging.Debug": "1.0.0",
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
"Microsoft.EntityFrameworkCore": "1.0.0",
"MySql.Data.Core": "7.0.4-IR-191",
"MySql.Data.EntityFrameworkCore": "7.0.4-IR-191",
"IdentityServer4": "1.0.0-rc2",
"AssoManager.Domain": "1.0.0-*",
"AssoManager.Service": "1.0.0-*",
"AssoManager.DataAccess": "1.0.0-*"
},
问题
我认为问题可能在于BaseRepository和IBaseRepository之间的继承。但我不知道哪里会是我的错误。如何更正此错误?
谢谢你的帮助:),
我发现Callum Bradbury的答案非常有用(谢谢你,Callum),但我认为更一般的答案可能适用于不同的情况。因此:
当您在给定的类中使用DI(依赖项注入)以及IoC(控制反转)容器来规则所有依赖项(这不是必需的,但这是一种常见情况)时,您必须确保每个可注入依赖项都在容器中注册,并且-可能-这通常是一个递归问题。
Exampli gratia,查找以下伪代码:
// A class which uses injected dependencies
class NeedSomeDependeciesToBeInjected
{
public NeedSomeDependeciesToBeInjected (
IThisIsReallyImportant important,
IThisIsUsefulButNotImportant useful) {}
}
// A complex dependency, which requires other injected dependency
// (So, yes, recursion...)
class ThisIsReallyImportant : IThisIsReallyImportant
{
public ThisIsReallyImportant (
IThisIsRequiredToBecomeImportant required) {}
}
// A dependency, which does not require other injected dependency,
// but is required for another dependency
class ThisIsRequiredToBecomeImportant : IThisIsRequiredToBecomeImportant
{
public ThisIsRequiredToBecomeImportant () {}
}
// A simple dependency, which does not require other injected dependency,
// and is not required for others
class ThisIsUsefulButNotImportant : IThisIsUsefulButNotImportant
{
public ThisIsUsefulButNotImportant () {}
}
class Program
{
private readonly WeaponOfChoiceInIoC container;
public void ConfigureDependencies()
{
container = new WeaponOfChoiceInIoC();
container.Register(IThisIsRequiredToBecomeImportant,
ThisIsRequiredToBecomeImportant);
container.Register(IThisIsReallyImportant,
ThisIsReallyImportant );
container.Register(IThisIsUsefulButNotImportant,
ThisIsUsefulButNotImportant );
}
public void MethodToPlayWithDependencies()
{
var toy = container.GetInstance(NeedSomeDependeciesToBeInjected);
}
}
您将UnitRepository注册为IUnitRepository,但请求您的IoC解析UnitRepository。它没有注册,所以它失败了。
尝试让UnitService使用IUnitRepository而不是UnitRepository,这样可以解决问题(请原谅这个双关语)。
我有以下错误,我无法开始这门课,我想请你帮我解决它。 错误: 系统InvalidOperationException:无法解析“IcarusOnlineAPI”类型的服务。服务。电子邮件试图激活“IcarusOnlineAPI”时发送电子邮件。控制器。授权。AuthController’。在微软。扩展。依赖注入。ActivatorUtilities。Microsoft lambda\u metho
我正在尝试构建一个简单的api,作为对项目未来api的测试。但我一直有这个错误 InvalidOperationException:无法解析“AspnetCore\u WebApi”类型的服务。模型。TarefaContext“正在尝试激活”AspnetCore\u WebApi。模型。TarefaRepositorio’。 这是TarefaContext。反恐精英 TarefaRepositor
我刚开始使用Android Studio一周,它对我来说非常好,但当我今天开始使用Android Studio时,我得到了一个错误:“错误:重复类:mypackage”。R’。我以前在使用Eclipse时看到过这个错误,所以我尝试过几次重建项目并重新启动Android Studio,但都没有帮助。 在阅读了一些Stackoverflow问题后,我尝试删除R.java并再次重建,现在我在重建时没有收
无法解析类型java.lang.Object。它从必需的.class文件中间接引用
在我的ASP. NET Core应用程序中,我收到以下错误: 无效操作异常:在尝试激活“城市”时无法解析类型“城市”的服务。模型。IRepository。控制器。HomeController。 我是家庭控制器,我试图将城市的getter传递给视图,如下所示: 我有一个文件存储库。cs包含一个接口及其实现,如下所示: 我的启动类包含从模板生成的默认代码。我做了任何更改:
让我们考虑一个类: