我有一个微型ASP.NET项目,我在其中尝试使用Repository/UnitOfWork
体系结构原理。一切都应该正常进行,但是,我的StartUp
文件中的依赖性经常遇到问题。我不确定在这里哪里出问题了。非常感谢您的帮助。
错误:
处理请求时发生未处理的异常。 InvalidOperationException:尝试激活“ Project.Controllers.UsersController”时,无法解析类型为“ Project.UOW.IUnitOfWork”的服务。
以上错误仅在将IUnitOfWork作为依赖项注入启动文件中时发生。如果我添加所有三个依赖项,则在=>
的效果中会得到不同的错误“ HTTP错误502.3-错误的网关。指定的CGI应用程序遇到错误,服务器终止了该过程。”
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
IRepository:
public interface IRepository<TEntity> where TEntity : class
{
Task<TEntity> GetById(int id);
Task<IEnumerable<TEntity>> GetAll();
}
存储库:
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
private readonly DbContext _context;
public Repository(DbContext context)
{
_context = context;
}
public async Task<TEntity> GetById(int id)
{
return await _context.Set<TEntity>().FindAsync(id);
}
public async Task<IEnumerable<TEntity>> GetAll()
{
return await _context.Set<TEntity>().ToListAsync();
}
}
IUserRepository:
public interface IUserRepository : IRepository<User>
{
Task<IEnumerable<User>> GetAllUsers();
IEnumerable<User> GetUserById(int Id);
}
UserRepository:
public class UserRepository : Repository<User>, IUserRepository
{
public UserRepository(DbContext context)
: base(context)
{
}
public IEnumerable<User> GetUserById(int Id)
{
return Context.User.Where(p => p.UserId == Id).ToList();
}
public async Task<IEnumerable<User>> GetAllUsers()
{
return await Context.User.ToListAsync();
}
}
UnitOfWork:
public class UnitOfWork : IUnitOfWork
{
private DbContext _context;
public UnitOfWork(DbContext context)
{
_context = context;
User = new UserRepository(_context);
}
public IUserRepository User { get; set; }
public int Complete()
{
return _context.SaveChanges();
}
public void Dispose()
{
_context.Dispose();
}
}
IUnitOfWork:
public interface IUnitOfWork : IDisposable
{
IUserRepository User { get; set; }
int Complete();
}
启动:
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddTransient<IUserRepository, UserRepository>();
services.AddTransient(typeof(IRepository<>), typeof(Repository<>));
UserController:
public class UsersController : Controller
{
private IUnitOfWork _unitOfWork;
public UsersController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
// GET: Users
public async Task<IActionResult> Index()
{
var getAllUsers = _unitOfWork.User.GetAllUsers();
return View(await getAllUsers);
}
}
答案 0 :(得分:0)
这个问题似乎已经解决了,仅通过启动一个新项目即可。因此,谢谢大家的帮助!