如何在 C# 中使用具体参数注册开放泛型类型

问题描述 投票:0回答:1

我们可以对开放泛型类型进行依赖注入:

public interface IRepo<T, TKey> where T: class { ... }

public class RepoBase<T, TKey>: IRepo<T, TKey> where T: class {...}
// DI
services.AddScoped(typeof(IRepo<,>), typeof(RepoBase<,>));  

但我想让

RepoBase
有两种开放类型和一种具体类型:

public interface IRepo<T, TKey> where T: class { ... }

public class RepoBase<T, TKey, D>: IRepo<T, TKey> where T: class {...} where D : DbContext  // D is DbContext from EF 
{
   ...
}  

public class MyDbContext : DbContext { ... }
services.AddScoped(typeof(IRepo<,>), typeof(RepoBase<,,>));  // compiles, but what I want is the third type should be MyDbContext

services.AddScoped(typeof(IRepo<,>), typeof(RepoBase<,,MyDbContext>)); // doesn't compile, but this is what I want

那么如何注册开放泛型类型但提供部分具体类型呢?

c# .net asp.net-core dependency-injection
1个回答
0
投票

正如评论中已经提到的,您可以定义这样的类型:

public class RepoBaseWithMyContext<T1, T2> : RepoBase<T1, T2, MyDbContext>

然后像这样注册:

services.AddScoped(typeof(IRepo<,>), typeof(RepoBaseWithMyContext<,>));
© www.soinside.com 2019 - 2024. All rights reserved.