How to resolve generic interface to generic implementation when using dependency injection?

元气小坏坏 提交于 2021-02-11 13:01:53

问题


I have created a generic repository that I want to be used in a service.

public abstract class AbstractBaseRepository<TEntity, TEntityKey>
        : IBaseRepository<TEntity, TEntityKey>
        where TEntity : class, IBaseEntity<TEntityKey>, new() { /* some code */ }

And the interface:

public interface IBaseRepository<TEntity, TEntityKey> { /* some code */ }

On my service I inject the repository like this:

public class TenantsService : AbstractBaseService<TenantEntity, int>
{
    public TenantsService(IBaseRepository<TenantEntity, int> tenantsRepository)
        : base(tenantsRepository) { }
}

On my startup, on the ConfigureServices method, I have:

services.AddScoped(typeof(IBaseRepository<,>), typeof(AbstractBaseRepository<,>));  

I added this startup code based on the following two answers:

https://stackoverflow.com/a/33567396

https://stackoverflow.com/a/43094684

When I run the application I am getting the following error:

Cannot instantiate implementation type 'Playground.Repositories.Base.AbstractBaseRepository`2[TEntity,TEntityKey]' for service type 'Playground.Repositories.Base.IBaseRepository`2[TEntity,TEntityKey]'


回答1:


Try this:

services.AddScoped(typeof(IBaseRepository<TenantEntity, int>), typeof(TenantsService));

As Kirk Larkin mentioned in the comments, you're telling it to instantiate an abstract class for services.AddScoped(typeof(IBaseRepository<,>), typeof(AbstractBaseRepository<,>)); which it can't do.



来源:https://stackoverflow.com/questions/53101127/how-to-resolve-generic-interface-to-generic-implementation-when-using-dependency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!