【问题标题】:.NET CORE 2.0 Unable to resolve service for type while attempting to activate.NET CORE 2.0 在尝试激活时无法解析服务类型
【发布时间】: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&lt;Token, long&gt;吗?
  • 附带说明,这里是不同 DI 生命周期的文档:docs.microsoft.com/en-us/aspnet/core/fundamentals/…

标签: asp.net-core .net-core asp.net-core-webapi


【解决方案1】:

请确保您在 Startup.cs 内的 DI 容器中注册依赖项

public class Startup
{  
    ...

    public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddScoped<IDataRepository<Token, long>, TokenManager>();
        ...
    }
}

【讨论】:

    猜你喜欢
    • 2021-12-25
    • 2020-07-01
    • 1970-01-01
    • 2018-04-06
    • 2021-09-23
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多