Core利用原生服务控制反转注入泛型类

时间:2025-02-07 09:43:21

在 mvc中,为了减少重复代码,会用到自己写的泛型类,比如IRepository<T>和EfRepository<T>


在中,有几个控制反转例子

            // Add framework services.
            <ApplicationDbContext>(options =>
                (("DefaultConnection")));

            <ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            ();

            // Add application services.
            <IEmailSender, AuthMessageSender>();
            <ISmsSender, AuthMessageSender>();
但是,并没有控制反转泛型类的例子,因为,明天2017年3月7号,VS2017正式版才会发布,现在的网上的例子,讨论还不是很多。

我通过研究 mvc的源码,发现在EFCore项目Infrastructure->class ServiceCollectionMap->

  public virtual ServiceCollectionMap TryAddTransient([NotNull] Type serviceType, [NotNull] Type implementationType)
            => TryAdd(serviceType, implementationType, );
也就是说,可以传入自己读取好的type类型。

(typeof(IRepository<>), typeof(EfRepository<>));
补充:注入泛型类时记得加<>尖括号。