您的位置:首页 > 编程语言 > ASP

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

2017-03-06 15:40 896 查看
在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<>));
补充:注入泛型类时记得加<>尖括号。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐