下面我们给 IServiceCollection 写扩展方法
首先新建一个静态类 名称未 services,代码如下:
1 public static class service 2 { 3 public static IServiceCollection registerService(this IServiceCollection services) 4 { 5 6 services.AddSession(); 7 8 services.AddControllersWithViews(); 9 services.AddSingleton<hy_contentService>(); 10 services.AddSingleton<UserService>(); 11 services.AddSingleton<hy_roomService>(); 12 services.AddSingleton<hy_classService>(); 13 services.AddSingleton<hy_groupService>(); 14 //sqlserver_personService 15 services.AddSingleton<sqlserver_personService>(); 16 services.AddSingleton<Town_countryService>(); 17 services.AddSingleton<sqlserver_departmentService>(); 18 //TypeService 19 services.AddHttpContextAccessor(); 20 services.AddRazorPages().AddRazorRuntimeCompilation(); 21 22 23 24 25 26 return services; 27 } 28 }View Code
在扩展类中新建一个 registerService方法 用于 扩展 ,方法签名如下:
public static IServiceCollection registerService(this IServiceCollection services)
完整代码如下:
1 public static IServiceCollection registerService(this IServiceCollection services) 2 { 3 //将服务注册都可以写到该扩展方法中 4 services.AddSession(); 5 6 services.AddControllersWithViews(); 7 services.AddSingleton<hy_contentService>(); 8 services.AddSingleton<UserService>(); 9 services.AddSingleton<hy_roomService>(); 10 services.AddSingleton<hy_classService>(); 11 services.AddSingleton<hy_groupService>(); 12 //sqlserver_personService 13 services.AddSingleton<sqlserver_personService>(); 14 services.AddSingleton<Town_countryService>(); 15 services.AddSingleton<sqlserver_departmentService>(); 16 //TypeService 17 services.AddHttpContextAccessor(); 18 services.AddRazorPages().AddRazorRuntimeCompilation(); 19 20 21 22 23 24 return services; 25 }
下面 在 startUp ConfigureServices方法中使用 扩展方法
1 public void ConfigureServices(IServiceCollection services) 2 { 3 DB.DB_ConnectionString = Configuration.GetConnectionString("mySqlStr"); 4 DB.DB_SqlserverConnectionString = Configuration.GetConnectionString("SqlServerStr"); //SqlServerStr 5 6 services.registerService(); //该处调用 扩展方法 registerService ,把注册各种服务都可以写入该方法内 ,增强程序可读性 ,同时能保持 ConfigureServices 方法可读性。层次、逻辑更清晰 7 8 }
扩展方法 定义及应用就写到这里!