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

来源:互联网 发布:青岛电视台网络电视 编辑:程序博客网 时间:2024/05/19 16:06

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


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

            // Add framework services.            services.AddDbContext<ApplicationDbContext>(options =>                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));            services.AddIdentity<ApplicationUser, IdentityRole>()                .AddEntityFrameworkStores<ApplicationDbContext>()                .AddDefaultTokenProviders();            services.AddMvc();            // Add application services.            services.AddTransient<IEmailSender, AuthMessageSender>();            services.AddTransient<ISmsSender, AuthMessageSender>();
但是,并没有控制反转泛型类的例子,因为,明天2017年3月7号,VS2017正式版才会发布,现在的网上的例子,讨论还不是很多。

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

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

services.AddTransient(typeof(IRepository<>), typeof(EfRepository<>));





0 0
原创粉丝点击