Jas*_*son 4 .net-core asp.net-core asp.net-core-webapi
我有一个IDataRepository.cs文件,其中包含一个接口及其实现,如下所示:
public interface IDataRepository<TEntity, U> where TEntity : class
{
IEnumerable<TEntity> GetAll();
TEntity Get(U id);
TEntity GetByString(string stringValue);
long Add(TEntity b);
long Update(U id, TEntity b);
long Delete(U id);
}
Run Code Online (Sandbox Code Playgroud)
我有另一个实现IDataRepository接口的类TokenManager.cs:
public class TokenManager : IDataRepository<Token, long>
{
ApplicationContext ctx;
public TokenManager(ApplicationContext c)
{
ctx = c;
}
//Get the Token Information by ID
public Token Get(long id)
{
var token = ctx.Token.FirstOrDefault(b => b.TokenId == id);
return token;
}
public IEnumerable<Token> GetAll()
{
var token = ctx.Token.ToList();
return token;
}
//Get the Token Information by ID
public Token GetByString(string clientType)
{
var token = ctx.Token.FirstOrDefault(b => b.TokenClientType == clientType);
return token;
}
public long Add(Token token)
{
ctx.Token.Add(token);
long tokenID = ctx.SaveChanges();
return tokenID;
}
}
Run Code Online (Sandbox Code Playgroud)
最后,我有一个控制器将所有东西放在一起,我的控制器文件看起来像这样:
[Route("api/[controller]")]
public class TokenController : Controller
{
private IDataRepository<Token, long> _iRepo;
public TokenController(IDataRepository<Token, long> repo)
{
_iRepo = repo;
}
// GET: api/values
[HttpGet]
public IEnumerable<Token> Get()
{
return _iRepo.GetAll();
}
// GET api/values/produccion
[HttpGet("{stringValue}")]
public Token Get(string stringValue)
{
return _iRepo.GetByString(stringValue);
}
}
Run Code Online (Sandbox Code Playgroud)
但问题是每次我尝试从我的API访问某些方法时,例如使用postman我得到错误:
InvalidOperationException异常:无法解析为类型FECR_API.Models.Repository.IDataRepository`2 [FECR_API.Models.Token,System.Int64]的服务,同时试图激活; FECR_API.Controllers.TokenController
我尝试在ConfigureServices中使用类似的东西,但得到转换错误
services.AddScoped<IDataRepository, TokenManager>();
Run Code Online (Sandbox Code Playgroud)
知道我做错了什么吗?
Win*_*Win 17
请确保在DI容器内注册依赖项 Startup.cs
public class Startup
{
...
public void ConfigureServices(IServiceCollection services)
{
...
services.AddScoped<IDataRepository<Token, long>, TokenManager>();
...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17967 次 |
| 最近记录: |