Net Core 扩展使用Refit

 标签(空格分隔): 未分类


在.net core 2.1当中,目前可以是用HttpClientFactory进行Http的调用,它的使用方法我不再多说,具体参见(https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.2#consumption-patterns)。微软的官网写的非常详细了。

在调用过程中使用Refit可以进行强类型的客户端调用,个人比较喜欢这个。目前还有一个组件是老九大佬写的一个类似的客户端(https://github.com/dotnetcore/WebApiClient)

在WebApi当中使用Refit。

        public void ConfigureServices(IServiceCollection services)         {             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);              services.AddHttpClient("github", c =>             {                 c.BaseAddress = new Uri("https://api.github.com");             })     .AddTypedClient(c => Refit.RestService.For<IGitHubApi>(c));              services.AddRefitClient<IGitHubApi>();         }                  

接口的定义为:

    [Headers("User-Agent: Refit Integration Tests")]     //[RefitClient("github")]     public interface IGitHubApi     {         [Get("/users/{username}")]         Task<User> GetUser(string userName);     }

当我们有很多接口需要注入的时候,就得写很多的类似强类型的AddRefitClient的代码,个人觉得非常的麻烦。是否能够根据标签程序集进行批量注入。
Refit的注入,其实注入的是一个RestService

        public static IHttpClientBuilder AddRefitClient<T>(this IServiceCollection services, RefitSettings settings = null) where T : class         {             services.AddSingleton(provider => RequestBuilder.ForType<T>(settings));              return services.AddHttpClient(UniqueName.ForType<T>())                            .AddTypedClient((client, serviceProvider) => RestService.For<T>(client, serviceProvider.GetService<IRequestBuilder<T>>()));         }

具体的类型是在代码编译阶段用BuildTask生成了带有RefitHttpAttribute的接口类型的实体类。

具体创建的类型如下:

[ExcludeFromCodeCoverage, DebuggerNonUserCode, Preserve] internal class AutoGeneratedIGitHubApi : IGitHubApi {     // Fields     [CompilerGenerated, DebuggerBrowsable(0)]     private HttpClient <Client>k__BackingField;     private readonly IRequestBuilder requestBuilder;      // Methods     public AutoGeneratedIGitHubApi(HttpClient client, IRequestBuilder requestBuilder)     {         this.Client = client;         this.requestBuilder = requestBuilder;     }      public virtual Task<User> GetUser(string userName)     {         object[] objArray1 = new object[] { userName };         object[] objArray = objArray1;         Type[] typeArray1 = new Type[] { typeof(string) };         return (Task<User>) this.requestBuilder.BuildRestResultFuncForMethod("GetUser", typeArray1, null)(this.Client, objArray);     }      // Properties     public HttpClient Client { get; protected set; } } 

目前我们要解决的是如何批量的进行注入的问题:个人在Refit的源码上添加了一些代码以支持批量注入

   //配置的实体     public class ApiSettings     {         public List<ApiOption> Apis { 

                    
                
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信