gpt4 book ai didi

c# - 验证服务描述符时出错 'ServiceType: INewsRepository Lifetime: Singleton ImplementationType: NewsRepository' :

转载 作者:行者123 更新时间:2023-12-04 06:39:53 25 4
gpt4 key购买 nike

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

Bmu.Mode 'this is for model to create database'

Bmu.Repo 'it have 2 folder for repository include contract/InewsRepository.cs' and 'Repository/NewsRepository' for implement Interface

Bmu.Api for invoke data from Repo project



模型项目中的新闻类
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 中实现接口(interface)
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 项目时
这是我的 Controller
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: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: bmu.repo.Contracts.INewsRepository Lifetime: Singleton ImplementationType: bmu.repo.IRepository.NewsRepository': Unable to resolve service for type 'bmu.model.BmuContext' while attempting to activate 'bmu.repo.IRepository.NewsRepository'.)



也因为多项目添加 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);
}
}
}

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

最佳答案

首先,您需要更改:

services.AddSingleton<INewsRepository, NewsRepository>();

到:
services.AddTransient<INewsRepository, NewsRepository>();

其次,你需要注入(inject) IMemoryCache而不是 MemoryCacheNewsRepository .

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

1.启动.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;
}
//...
}

关于c# - 验证服务描述符时出错 'ServiceType: INewsRepository Lifetime: Singleton ImplementationType: NewsRepository' :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59328439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com