我正在尝试使用NLayer架构和通用存储库在.net核心中开发api。
当我尝试获取数据时,我看到一个错误。
我的错误 在处理请求时发生未处理的异常。 InvalidOperationException:尝试激活“ Fenerbahce.API.Controllers.PlayerController”时无法解析“ Fenerbahce.Business.Abstract.IPlayerManager”类型的服务。
IPlayerManger:
public interface IPlayerManager
{
Task<IEnumerable<Player>> GetAllPlayers();
Task<Player> GetPlayerById(int id);
Task<Player> CreatePlayer(Player player);
Task UpdatePlayer(Player playerToBeUpdated,Player player);
Task DeletePlayer(Player player);
}
PlayerManager
私有只读IUnitOfWork _unitOfWork;
public PlayerManager(IUnitOfWork unitOfWork)
{
this._unitOfWork = unitOfWork;
}
public async Task<Player> CreatePlayer(Player player)
{
await _unitOfWork.Players.AddAsync(player);
await _unitOfWork.CommitAsync();
return player;
}
public async Task DeletePlayer(Player player)
{
_unitOfWork.Players.Remove(player);
await _unitOfWork.CommitAsync();
}
public async Task<IEnumerable<Player>> GetAllPlayers()
{
return await _unitOfWork.Players.GetAllAsync();
}
public async Task<Player> GetPlayerById(int id)
{
return await _unitOfWork.Players.GetByIdAsync(id);
}
public async Task UpdatePlayer(Player playerToBeUpdated, Player player)
{
playerToBeUpdated.updatedAt = DateTime.Now;
await _unitOfWork.CommitAsync();
}
}
IUnitOfWork
public interface IUnitOfWork : IDisposable
{
IBranchDal Branchs { get; }
ICoachDal Coachs { get; }
IPlayerDal Players {get;}
ITeamDal Teams {get;}
Task<int> CommitAsync();
}
EfUnitOfWork.cs
public class EfUnitOfWork : IUnitOfWork
{
private readonly FBDbContext _context;
private EfBranchDal _branchDal;
private EfCoachDal _coachDal;
private EfPlayerDal _playerDal;
private EfTeamDal _teamDal;
public EfUnitOfWork(FBDbContext context)
{
this._context = context;
}
public IBranchDal Branchs => _branchDal = _branchDal ?? new EfBranchDal(_context);
public ICoachDal Coachs => _coachDal = _coachDal ?? new EfCoachDal(_context);
public IPlayerDal Players => _playerDal = _playerDal ?? new EfPlayerDal(_context);
public ITeamDal Teams => _teamDal = _teamDal ?? new EfTeamDal(_context);
public async Task<int> CommitAsync()
{
return await _context.SaveChangesAsync();
}
public void Dispose()
{
_context.Dispose();
}
}
PlayerController.cs
public class PlayerController:ControllerBase
{
private readonly IPlayerManager _playerManager;
private readonly IMapper _mapper;
public PlayerController(IPlayerManager playerManager, IMapper mapper)
{
this._playerManager = playerManager;
this._mapper = mapper;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<PlayerDTO>>> ListAllPlayers()
{
var players = await _playerManager.GetAllPlayers();
var playerResources = _mapper.Map<IEnumerable<Player>,
IEnumerable<PlayerDTO>>(players);
return Ok(playerResources);
}
}
感谢您的帮助。
答案 0 :(得分:0)
显然,缺少依赖项注入容器。您可以为此使用unity / ninject / autofac,并可以从Google了解如何使用。
还有萨曼·赫尔德