【发布时间】:2018-11-04 04:37:24
【问题描述】:
我有一个 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);
}
我有另一个实现 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;
}
}
最后,我有一个控制器可以将所有东西放在一起,我的控制器文件如下所示:
[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);
}
}
但问题是每次我尝试从我的 API 访问某些方法时,例如使用邮递员,我都会收到错误:
InvalidOperationException:尝试激活时无法解析 FECR_API.Models.Repository.IDataRepository`2[FECR_API.Models.Token,System.Int64] 类型的服务;FECR_API.Controllers.TokenController
我尝试在 ConfigureServices 中使用类似的东西,但出现转换错误
services.AddScoped<IDataRepository, TokenManager>();
知道我做错了什么吗?
【问题讨论】:
-
您在 ConfigureServices 中添加了哪一行?
-
哦,对不起,我忘记了。这:services.AddScoped
(); -
你试过
IDataRepository<Token, long>吗? -
附带说明,这里是不同 DI 生命周期的文档:docs.microsoft.com/en-us/aspnet/core/fundamentals/…
标签: asp.net-core .net-core asp.net-core-webapi