【发布时间】:2021-01-17 19:37:09
【问题描述】:
为简单起见,我想将通用存储库注入到视图模型中。我将 ViewModel 和 Repository 添加到服务集合中,ViewModel 依赖于 Repository。根据我的阅读,应该自动解析 ViewModel 的构造函数参数,因为它使用的是 IConfiguration。我已经尝试在 Services 中显式实例化 ViewModel,但仍然出现相同的运行时错误,并且在创建存储库的另一个实例时似乎无法达到目的。
Repository/IRepository 看起来像这样
public class Repository<TPoco, TDatabaseConnection> : IRepository<TPoco, TDatabaseConnection>
where TPoco : class
where TDatabaseConnection : IDbConnection, new()
{
public Repository(IConfiguration configuration, string connectionName = "DefaultConnection" )//SqlConnectionConfiguration configuration) //(string connectionString)
{
_connectionString = configuration.GetConnectionString(connectionName);
_configuration = configuration;
}
...
查看模型
public class PersonViewModel
{
private IRepository<Person, IDbConnection> _PersonRepository;
public List<Person> Persons { get; set; }
public PersonViewModel(IRepository<Person, IDbConnection> personRepository)
{
_PersonRepository=personRepository;
}
...
在 Startup.cs 文件中,我添加如下服务:
services.AddScoped<IRepository<Person, SQLiteConnection>, Repository<Person, SQLiteConnection>>();
services.AddScoped<PersonViewModel>(); //runtime errors here
我收到两个运行时错误 (System.AggregateException)
Inner Exception 1:
InvalidOperationException: Error while validating the service descriptor 'ServiceType: BlazorInjection.ViewModels.PersonViewModel Lifetime: Scoped ImplementationType: BlazorInjection.ViewModels.PersonViewModel': Unable to resolve service for type 'DapperRepository.IRepository`2[BlazorInjection.Models.Person,System.Data.IDbConnection]' while attempting to activate 'BlazorInjection.ViewModels.PersonViewModel'.
Inner Exception 2:
InvalidOperationException: Unable to resolve service for type 'DapperRepository.IRepository`2[BlazorInjection.Models.Person,System.Data.IDbConnection]' while attempting to activate 'BlazorInjection.ViewModels.PersonViewModel'.
我错过了一个概念吗?我该如何纠正这个问题?
【问题讨论】:
-
这可能对stevejgordon.co.uk/…有帮助
标签: c# asp.net-core .net-core dependency-injection blazor