动手造轮子:实现一个简单的依赖注入(一) (4)

因为 GetService 返回是 object , 不是强类型的,所以为了使用起来方便,定义了几个扩展方法,类似于微软的依赖注入框架里的 GetService<TService>()/GetServices<TService>()/GetRequiredService<TService>()

/// <summary> /// ResolveService /// </summary> /// <typeparam>TService</typeparam> /// <param>serviceProvider</param> /// <returns></returns> public static TService ResolveService<TService>([NotNull]this IServiceProvider serviceProvider) => (TService)serviceProvider.GetService(typeof(TService)); /// <summary> /// ResolveRequiredService /// throw exception if can not get a service instance /// </summary> /// <typeparam>TService</typeparam> /// <param>serviceProvider</param> /// <returns></returns> public static TService ResolveRequiredService<TService>([NotNull] this IServiceProvider serviceProvider) { var serviceType = typeof(TService); var svc = serviceProvider.GetService(serviceType); if (null == svc) { throw new InvalidOperationException($"service had not been registered, serviceType: {serviceType}"); } return (TService)svc; } /// <summary> /// Resolve services /// </summary> /// <typeparam>TService</typeparam> /// <param>serviceProvider</param> /// <returns></returns> public static IEnumerable<TService> ResolveServices<TService>([NotNull]this IServiceProvider serviceProvider) => serviceProvider.ResolveService<IEnumerable<TService>>(); More

后面还更新了一版,主要优化性能,目前来说还不太满意,暂时这里先不提了

Reference

Dynamic Casting using Reflection

https://github.com/WeihanLi/WeihanLi.Common/blob/dev/test/WeihanLi.Common.Test/DependencyInjectionTest.cs

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzypyz.html