通过接口注入泛型类

时间:2017-01-04 19:08:21

标签: c# spring generics dependency-injection

如何通过Spring通过接口注入泛型类?

我有一个像这样的通用界面:

public interface IGenericRepository<in TEntity> where TEntity : class

以及实现此目的的其他接口:

public interface IEntity1Repository : IGenericRepository<Entity1>

在我的服务中,我使用该界面

public class Service1 : IService1
{
    private readonly IEntity1Repository _repo;

    public Service1(IEntity1Repository repo)
    {
        _repo = repo;
    }

    public void Create(Entity1 entity)
    {
        _repo.Create(entity);
    }

    public void Update(Entity1 entity)
    {
        _repo.Update(entity);
    }

    public void Delete(Entity1 entity)
    {
        _repo.Delete(entity);
    }
}

我为通用存储库创建了一个通用类,如下所示:

public class GenericRepository<TEntity, TDbContext> : IGenericRepository<TEntity> where TEntity : class
    where TDbContext : DbContext
{
    public GenericRepository(TDbContext db)
    {
        Db = db;
    }

    public TDbContext Db { get; set; }

    public async Task<int> Create(TEntity entity)
    {
        Db.Entry(entity).State = EntityState.Added;
        return await Db.SaveChangesAsync();
    }

    public async Task<int> Update(TEntity entity)
    {
        Db.Entry(entity).State = EntityState.Modified;
        return await Db.SaveChangesAsync();
    }

    public async Task<int> Delete(TEntity entity)
    {
        Db.Entry(entity).State = EntityState.Deleted;
        return await Db.SaveChangesAsync();
    }
}

我想用Spring这样直接将这个类注入Service1:

<object id="MyDbContext" type="springTest.Test.MyDbContext, springTest" singleton="false" />
<object id="Repository" type="springTest.Test.Repositories.GenericRepository, springTest" singleton="false">
  <constructor-arg ref="MyDbContext" />
</object>

<!-- Services -->
<object id="Service1" type="springTest.Test.Services.Service1, springTest" singleton="false">
  <constructor-arg ref="Repository" />
</object>
<object id="Service2" type="springTest.Test.Services.Service2, springTest" singleton="false">
  <constructor-arg ref="Repository" />
</object>

执行此操作时,我收到此错误:{"Could not load type 'springTest.Test.Repositories.GenericRepository' from assembly 'springTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.":"springTest.Test.Repositories.GenericRepository"}

是否可以在不创建继承GenericRepository的空类的情况下对其进行存档?

项目可以在这里下载:Dropbox download link,只需记住点击“包含nuget包”。

0 个答案:

没有答案