我有一个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>();
知道我做错了吗?
答案 0 :(得分:13)
请确保在Startup.cs
public class Startup
{
...
public void ConfigureServices(IServiceCollection services)
{
...
services.AddScoped<IDataRepository<Token, long>, TokenManager>();
...
}
}