For simplicity sake, I'd like to Inject a generic repository into a view model. I'm add the the ViewModel and Repository to the services collection and the ViewModel depends on the Repository. From what I've read, the ViewModel's constructor parameters should be resolved automatically, since it's using IConfiguration. I've tried explicitly instantiating the ViewModel in the Services, but still get the same runtime error and seems to defeat the purpose as I'm creating another instance of the repository.
Repository/IRepository look like this
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;
}
...
View Model
public class PersonViewModel
{
private IRepository<Person, IDbConnection> _PersonRepository;
public List<Person> Persons { get; set; }
public PersonViewModel(IRepository<Person, IDbConnection> personRepository)
{
_PersonRepository=personRepository;
}
...
In Startup.cs file I add the services like so:
services.AddScoped<IRepository<Person, SQLiteConnection>, Repository<Person, SQLiteConnection>>();
services.AddScoped<PersonViewModel>(); //runtime errors here
I'm getting two runtime errors (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'.
Am I missing a concept? How do I correct this?