这个问题通常是由于在 ASP.NET 注入过程中的配置错误导致的。要解决这个问题,可以考虑以下步骤:
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
public class MyController : Controller
{
private readonly IService1 _service1;
private readonly IService2 _service2;
private readonly IService3 _service3;
private readonly IGenericRepository _repository;
public MyController(IService1 service1, IService2 service2, IService3 service3, IGenericRepository repository)
{
_service1 = service1;
_service2 = service2;
_service3 = service3;
_repository = repository;
}
// ...
}
例如,在使用“Services.AddScoped(typeof(IGenericRepository<>),typeof(GenericRepository<>))”来注册泛型仓储库时,在服务类型和泛型仓储库的实现中都使用了正确的泛型类型。
public interface IMyService
{
// ...
}
public class MyService : IMyService where T : BaseEntity
{
private readonly IGenericRepository _repository;
public MyService(IGenericRepository repository)
{
_repository = repository;
}
// ...
}
public class MyController : Controller
{
private readonly IMyService _service;
public MyController(IMyService service)
{
_service = service;
}
// ...
}