【问题标题】:Error while validating the service descriptor 'ServiceType: INewsRepository Lifetime: Singleton ImplementationType: NewsRepository':验证服务描述符“ServiceType:INewsRepository Lifetime:Singleton ImplementationType:NewsRepository”时出错:
【发布时间】:2019-12-13 19:03:54
【问题描述】:

我尝试使用存储库模式从我的数据库中获取数据 我有 3 个项目

Bmu.Mode '这是用于创建数据库的模型'

Bmu.Repo '它有 2 个用于存储库的文件夹,包括 contract/InewsRepository.cs' 和 'Repository/NewsRepository' 用于实现接口

用于从 Repo 项目调用数据的 Bmu.Api

模型项目中的新闻类

namespace bmu.model
{
   public class News
   {
    public int Id { get; set; }

    public string SubTitle { get; set; }

    public string Title { get; set; }

    public string Summery { get; set; }
  }
}

模型项目中的上下文类

namespace bmu.model
 {
   public class BmuContext : DbContext
    {
       public BmuContext(DbContextOptions<BmuContext> options): base(options)
      {

      }
    public DbSet<News> News { get; set; }
   }
}

我在 Repo 项目中的界面

namespace bmu.repo.Contracts
{
  public interface INewsRepository
  {
    Task<IEnumerable<News>> GetAllAsync();
    Task<IEnumerable<News>> GetAllActiveAsync();
  }
}

在 bmu.repo 中实现接口

namespace bmu.repo.IRepository
{
 public class NewsRepository : INewsRepository
 {
    private readonly BmuContext _context;
    private readonly MemoryCache _memoryCache;

    public NewsRepository(BmuContext context, MemoryCache memoryCache)
    {
        _context = context;
        _memoryCache = memoryCache;
    }
    public async Task<IEnumerable<News>> GetAllAsync()
    {
        return await _context.News.ToListAsync(); 
    }
    public async Task<IEnumerable<News>> GetAllActiveAsync()
    {
      return   await _context.News.Where(x => x.Active).ToListAsync();
    }

}
}

同时添加

services.AddControllers(); 
        services.AddSingleton<INewsRepository, NewsRepository>();

在 Api 项目启动中 这是我的控制器

namespace bmu.api.Controllers
{
[ApiController]
[Route("[controller]")]
public class NewsController : ControllerBase
{
     private readonly ILogger<NewsController> _logger;
     private readonly INewsRepository _newsRepository;

    public NewsController(ILogger<NewsController> logger,INewsRepository newsRepository)
    {
        _logger = logger;
        _newsRepository = newsRepository; 
    }
    [HttpGet]
    public async Task<IEnumerable<News>> Get()
    {
        return await _newsRepository.GetAllActiveAsync();
    }
}
}

但在运行项目时出现此错误

AggregateException:无法构造某些服务(验证服务描述符“ServiceType:bmu.repo.Contracts.INewsRepository Lifetime:Singleton ImplementationType:bmu.repo.IRepository.NewsRepository”时出错:无法解析服务类型尝试激活“bmu.repo.IRepository.NewsRepository”时出现“bmu.model.BmuContext”。)

也因为多项目添加了 DbContext

更新:

namespace bmu.model
{
public class BmuContextFactory : IDesignTimeDbContextFactory<BmuContext>
{
    public BmuContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<BmuContext>();
        optionsBuilder.UseSqlite("Data Source=bmu.db");

        return new BmuContext(optionsBuilder.Options);
    }
}
}

这个错误有什么解决办法吗?

【问题讨论】:

    标签: c# asp.net-core-mvc repository repository-pattern asp.net-core-3.0


    【解决方案1】:

    首先,你需要改变:

    services.AddSingleton<INewsRepository, NewsRepository>();
    

    收件人:

    services.AddTransient<INewsRepository, NewsRepository>();
    

    其次,你需要在NewsRepository中注入IMemoryCache而不是MemoryCache。

    这是一个简单的演示,如下所示:

    1.Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddSession();
        services.AddTransient<INewsRepository, NewsRepository>();
        services.AddDbContext<BmuContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("Connectionstring")));
        services.AddMemoryCache();
    }
    

    2.appsettings.json:

    "ConnectionStrings": {
        "Connectionstring": "Server=(localdb)\\mssqllocaldb;Database=Bmu;Trusted_Connection=True;MultipleActiveResultSets=true"  
    }
    

    3.NewsRepository:

    public class NewsRepository : INewsRepository
    {
        private readonly BmuContext _context;
        private readonly IMemoryCache _memoryCache;
    
        public NewsRepository(BmuContext context, IMemoryCache memoryCache)
        {
            _context = context;
        }
        //...
    }
    

    【讨论】:

    • 我确实认为,删除“private readonly IMemoryCache _memoryCache;”从存储库和 avery 认为工作正常
    • 如果我的回答有帮助,你能accept as answer吗?
    【解决方案2】:

    您的 API 中存在生命周期类型不匹配。 EntityFramework DbContext 是一个范围服务,您不能拥有 NewsRepository 的单例实例,因为它依赖于为每个请求生成的实例。

    您要么必须将 NewsRepository 用作范围服务,要么重组您的依赖解决方案,如此 SO 答案所示:Use DbContext in ASP .Net Singleton Injected Class

    【讨论】:

    • 我使用 services.AddScoped();但又得到这个错误
    • 你是如何注册你的 BmuContext 的?
    • services.AddDbContext();同时更新我的​​问题
    • 我看到您只是在设置设计时选项,而不是在 Startup.cs 中。我期望一个 services.AddDbContext(options => options.UseSqlite(your connection string));而是
    【解决方案3】:

    我正在添加 singleton 服务,该服务正在注入 DbContext 类。

    services.AddSingleton<WeatherForecastService>();
    

    我将上面更改为下面(添加了transient 服务范围)并且它起作用了。

    services.AddTransient<FoodItemService>();
    

    【讨论】:

      【解决方案4】:

      喜欢 Sotiris Koukios-Panopoulos -san 评论

      我看到您只是在设置设计时选项,而不是在您的 Startup.cs 中。我希望:

      services.AddDbContext<BmuContext>(options => options.UseSqlite("your connection string"));
      

      改为。

      就我而言,我忘了在我的Startup.cs 中设置它

      services.AddDbContext<myDbContext>(o => o.UseSqlServer(myConnectionString));
      

      我忘了提这个,因为我使用的是接口服务

      services.AddScoped<IMyTruckService, MyTruckService>();
      

      【讨论】:

        【解决方案5】:

        我的错误是我注入的是 service class 而不是 interface

        原来是

          //This is wrong
        Private readonly DataSerive _dataService;
        public void EmployeeHandler(DataSerive dataService)
        {
        _dataService = dataService;
        }
        

        但应该是的

         //This is correct
        Private readonly IDataSerive _dataService;
        public void EmployeeHandler(IDataSerive dataService)
        {
        _dataService = dataService;
        }
        

        这里的DataService是处理操作的类 IDataService 是 接口

        【讨论】:

          【解决方案6】:

          我有两个 dbcontext,忘记在 startup.cs 文件中提及这一点

          services.AddDbContext<Abc>(option => option.UseSqlServer(Configuration.GetConnectionString("ConStr")));
          

          【讨论】:

          • 欢迎来到 SO。目前尚不清楚您的帖子是否回答了原始问题。如果您认为您的帖子回答了这个问题,请详细说明原因和方式
          【解决方案7】:

          因为

              private readonly IMemoryCache _memoryCache;
          

          当我删除它时,每个都认为工作正常

          【讨论】:

          • 你的回答不合逻辑。
          • 我认为是因为没有在service的startup.cs中注册IMemoryCache,符合逻辑
          • IMemoryCache 是否注册在 startup.cs 中?
          • 另外,您应该在 Rena 的答案上签名作为已接受的答案
          猜你喜欢
          • 2023-03-08
          • 2021-06-06
          • 1970-01-01
          • 1970-01-01
          • 2020-11-04
          • 2021-11-10
          • 2021-07-09
          • 1970-01-01
          • 2022-06-28
          相关资源
          最近更新 更多