当泛型类型未知时,AddTransient到IServiceCollection

时间:2017-08-06 11:15:23

标签: c# .net entity-framework generics asp.net-web-api2

在我的WebApi Core中,Repository是通过构造函数注入。

//In the application, Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<MyContext>(options => 
        options.UseSqlServer(_config["ConnectionStrings:myConnection"]));
    services.AddDataAccess<MyContext>();
    services.AddMvc();
}

//In the controller
public class ValuesController : Controller
{
    readonly IRepository<Customer> _repository;

    public ValuesController(IRepository<Customer> repository)
    {
       _repository = repository;
    }
}

见下面的通用DAL。我收到了一个错误: services.AddTransient 使用泛型类型“GenericEntityRepository”需要2个类型参数

然后我需要这样的话:

services.AddTransient(typeof(IRepository<TEntity>), typeof(GenericEntityRepository<TEntityContext, TEntity>));

但是当我这样做时,我得到错误:

  • 未找到TEntity
  • TEntityContext必须是具有公共无参数构造函数的非抽象类型,才能在泛型类型中将其用作参数'TContext' 或方法'GenericEntityRepository'

我根本没有看到如何解决这个问题。

//In my Generic DAL
public static class ServiceCollectionExtentions
{
    public static IServiceCollection AddDataAccess<TEntityContext>(this IServiceCollection services)
        where TEntityContext : EntityContextBase<TEntityContext>
    {
        RegisterDataAccess<TEntityContext>(services);
        return services;
    }

    private static void RegisterDataAccess<TEntityContext>(IServiceCollection services)
        where TEntityContext : EntityContextBase<TEntityContext>
    {
        services.AddTransient(typeof(IRepository<>), typeof(GenericEntityRepository<>));
    }
}

public class EntityContextBase<TContext> : DbContext 
    where TContext : DbContext
{
    public EntityContextBase(DbContextOptions<TContext> options) : base(options) { }
}

public interface IRepository<TEntity>
{
    void Load();
}

public class GenericEntityRepository<TContext,TEntity> 
    : EntityRepositoryBase<TContext, TEntity> 
        where TEntity : BaseEntity, new()
        where TContext : DbContext, new()
{
    public GenericEntityRepository() : base(new TContext()) { }
}

public abstract class EntityRepositoryBase<TContext, TEntity> 
    : RepositoryBase<TContext>, IRepository<TEntity>
        where TContext : DbContext
        where TEntity : BaseEntity, new()
{
    protected EntityRepositoryBase(TContext context) : base(context)
    { }

    protected IQueryable<TEntity> QueryDb()
    {
        IQueryable<TEntity> query = Context.Set<TEntity>();

        return query;
    }

    public virtual void Load()
    {
        var result = QueryDb();
        result.Load();
    }
}

public class GenericEntityRepository<TContext,TEntity> 
    : EntityRepositoryBase<TContext, TEntity> 
        where TEntity : BaseEntity, new()
        where TContext : DbContext, new()
{
    public GenericEntityRepository() : base(new TContext()) { }
}

0 个答案:

没有答案