【发布时间】:2018-07-25 01:08:07
【问题描述】:
我想使用开放的通用实现和接口为 DI 注册以下项目。我知道下面的例子不起作用,以及我用MakeGenericType 或GetGenericArguments 尝试过的其他组合。我想简单地调用AddRepository<MyDbContext>,然后能够将我的实现注入到类中,而无需显式注册我正在使用的类型。
界面
public interface IRepository<TEntity>
{
}
实施
public class Repository<TEntity, TContext> : IRepository<TEntity>
where TEntity : class
where TContext : DbContext
{
}
注册
public static class RepositoryServiceCollectionExtensions
{
public static IServiceCollection AddRepository<TContext>(
this IServiceCollection services) where TContext : DbContext
{
services.TryAddScoped(
typeof(IRepository<>),
typeof(Repository< , TContext>));
return services;
}
}
【问题讨论】:
-
只有一个
Repository实现吗?还有一个 DbContext,还是多个上下文? -
根据注入时指定的任何类型,单个上下文将与多个存储库实现一起使用。
标签: asp.net-core dependency-injection