[英]Register Dependency Injection for generic class
所以這是我的應用程序結構:
我有這樣的存儲庫代碼
public interface IRepository<T> { }
public class Repository <T> { }
public interface ITestRepository : IRepository<Model> { }
public class TestRepository : Repository<Model>, ITestRepository { }
public interface ITest2Repository : IRepository<Model2> { }
public class Test2Repository : Repository<Model2>, ITest2Repository { }
我正在使用這個存儲庫作為我在 Web 中的服務,如下所示:
public class TestService : ITestService
{
private readonly ITestRepository testRepository;
private readonly ITest2Repository test2Repository;
public TestService(ITestRepository testRepository, ITest2Repository test2Repository)
{
this.testRepository = testRepository;
this.test2Repository = test2Repository;
}
}
現在,我正在像這樣在Startup.cs
注冊存儲庫。
services.AddScoped(typeof(IRepository<Model>), typeof(TestRepository));
services.AddScoped(typeof(IRepository<Model2>), typeof(Test2Repository));
services.AddScoped<ITestRepository, TestRepository>();
services.AddScoped<ITest2Repository, Test2Repository>();
我想簡化一下。 我最近搜索了注冊泛型類的方法,但它破壞了我的Program.cs
這是錯誤:
System.ArgumentException: '無法實例化服務類型'Application.Repositories.Interfaces.IRepository1[TEntity]'的實現類型'Application.Repositories.Repository1[TEntity]'。'
這是我注冊存儲庫的方式:
services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
services.AddScoped<ITestRepository, TestRepository>();
services.AddScoped<ITest2Repository, Test2Repository>();
TL; DR,有什么解決方案可以簡化我對該存儲庫的注冊?
您可以添加自己的擴展方法來簡化注冊:
static class ServiceCollectionExtensions
{
public static void AddRepository<TInterface, TRepository, TModel>(this IServiceCollection serviceCollection)
where TInterface : IRepository<TModel>
where TRepository : TInterface
{
services.AddScoped<TInterface, TRepository>();
services.AddScoped<IRepository<TModel>, TRepository>();
}
}
// usage:
services.AddRepository<ITestRepository, TestRepository, Model>();
對於您提到的錯誤,請參閱 Kirk 的評論:
看起來
Repository<T>
實際上並沒有實現IRepository<T>
- 我可以理解為什么 DI 系統對此不滿意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.