通用存储库的依赖注入
Dependency Injection for Generic Repository
用 3 个参数注册通用 class 的方法是什么
public interface ITest<T,V,VE>
{
}
public class TestRespository<T,V,VE>:ITest<T,V,VE>
{
}
我是这样注册的
services.AddScoped(typeof(ITest<,,>), typeof(ITest<,,>));
但无法像
一样进入 Constructor
service.GetService(typeof(ITest<TestClass, vTestClass, VETestClass>)) as ITest<TestClass, vTestClass, VETestClass>;
问题出在 AddScoped()
方法的调用上。您应该在第二个参数中传递实现类型,而不是接口本身的类型:
services.AddScoped(typeof(ITest<,,>), typeof(TestRespository<,,>));
services.AddScoped(typeof(ITest<,,>), typeof(ITest<,,>));
您需要 implementation
和 interface
而不是 interface
两次。您正在将 interface
注册为 interface
,因此它不能是 instantiated
。
services.AddScoped(typeof(ITest<,,>), typeof(TestRepository<,,>));
应该可以解决问题。
用 3 个参数注册通用 class 的方法是什么
public interface ITest<T,V,VE>
{
}
public class TestRespository<T,V,VE>:ITest<T,V,VE>
{
}
我是这样注册的
services.AddScoped(typeof(ITest<,,>), typeof(ITest<,,>));
但无法像
一样进入 Constructorservice.GetService(typeof(ITest<TestClass, vTestClass, VETestClass>)) as ITest<TestClass, vTestClass, VETestClass>;
问题出在 AddScoped()
方法的调用上。您应该在第二个参数中传递实现类型,而不是接口本身的类型:
services.AddScoped(typeof(ITest<,,>), typeof(TestRespository<,,>));
services.AddScoped(typeof(ITest<,,>), typeof(ITest<,,>));
您需要 implementation
和 interface
而不是 interface
两次。您正在将 interface
注册为 interface
,因此它不能是 instantiated
。
services.AddScoped(typeof(ITest<,,>), typeof(TestRepository<,,>));
应该可以解决问题。