最近在做公司老項目升級,要將原有的.net framework程序,升級到.net core平台,這個過程中就發現了一個問題,老項目在調用Service或者是Repository的時候都是直接new出來的,這顯然不符合我們.net core的規范,在.net core里邊更推薦用依賴注入,這就犯難了,如果我每個Service或者是Repository都在Starpup里面注冊,怕是要寫個幾百行,而且也很繁瑣。
今天上午,想了想要不求助一下大佬 @7thiny ,經過大佬的幫助,寫了一個用於全局注冊的方法,代碼如下:
public static class InjectHelper { /// <summary> /// Add Scoped from InterfaceAssembly and ImplementAssembly to the specified Microsoft.Extensions.DependencyInjection.IServiceCollection. /// </summary> /// <param name="services"></param> /// <param name="interfaceAssembly"></param> /// <param name="implementAssembly"></param> public static void AddScoped(this IServiceCollection services, Assembly interfaceAssembly, Assembly implementAssembly) { var interfaces = interfaceAssembly.GetTypes().Where(t => t.IsInterface); var implements = implementAssembly.GetTypes(); foreach (var item in interfaces) { var type = implements.FirstOrDefault(x => item.IsAssignableFrom(x)); if (type != null) { services.AddScoped(item, type); } } } /// <summary> /// Add AddSingleton from InterfaceAssembly and ImplementAssembly to the specified Microsoft.Extensions.DependencyInjection.IServiceCollection. /// </summary> /// <param name="services"></param> /// <param name="interfaceAssembly"></param> /// <param name="implementAssembly"></param> public static void AddSingleton(this IServiceCollection services, Assembly interfaceAssembly, Assembly implementAssembly) { var interfaces = interfaceAssembly.GetTypes().Where(t => t.IsInterface); var implements = implementAssembly.GetTypes(); foreach (var item in interfaces) { var type = implements.FirstOrDefault(x => item.IsAssignableFrom(x)); if (type != null) { services.AddSingleton(item, type); } } } /// <summary> /// Add AddTransient from InterfaceAssembly and ImplementAssembly to the specified Microsoft.Extensions.DependencyInjection.IServiceCollection. /// </summary> /// <param name="services"></param> /// <param name="interfaceAssembly"></param> /// <param name="implementAssembly"></param> public static void AddTransient(this IServiceCollection services, Assembly interfaceAssembly, Assembly implementAssembly) { var interfaces = interfaceAssembly.GetTypes().Where(t => t.IsInterface); var implements = implementAssembly.GetTypes(); foreach (var item in interfaces) { var type = implements.FirstOrDefault(x => item.IsAssignableFrom(x)); if (type != null) { services.AddTransient(item, type); } } } }
這樣我們就可以通過丟兩個Assembly進去,來幫助我們批量注冊服務,在Startup中調用方法如下:
services.AddScoped(Assembly.Load("xxxx.IService"), Assembly.Load("xxxx.Service")); services.AddScoped(Assembly.Load("xxxx.IService"), Assembly.Load("xxxx.Service"));