文章预览
在.NET中,注入泛型依赖项是一个常见的场景。 在依赖注入(DI)中使用泛型可以使得应用程序更加模块化、易于测试和扩展。 在ASP.NET Core中注册泛型服务 假设我们有一个需要注入的泛型接口 IRepository 和实现类 Repository 。 public interface IRepository { T GetById ( int id) ; } public class Repository : IRepository { public T GetById ( int id) { // 模拟从数据库中获取数据 return default(T); } } 接下来,我们需要将 Repository 注册到DI容器中。 在ASP.NET Core中,可以通过 AddTransient 、 AddScoped 或 AddSingleton 方法来注册服务。 为了支持泛型,我们可以使用以下方式: public void ConfigureServices ( IServiceCollection services ) { // 注册泛型服务 services.AddTransient(typeof(IRepository < >), typeof(Repository < >)); } 这段代码做了以下几
………………………………