取消

在linqpad环境中使用Refit

在linqpad中使用Refit报错.


问题

在linqpad中使用Refit报错:InvalidOperationException: xxx doesn’t look like a Refit interface. Make sure it has at least one method with a Refit HTTP method attribute and Refit is installed in the project.

解决

  1. nuget引用Castle.Core包
  2. 添加一个代理生成类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class ProxyRestService
{
	static readonly ProxyGenerator Generator = new ProxyGenerator();

	public static T For<T>(HttpClient client)
		where T : class
	{
		if (!typeof(T).IsInterface)
		{
			throw new InvalidOperationException("T must be an interface.");
		}

		var interceptor = new RestMethodInterceptor<T>(client);
		return Generator.CreateInterfaceProxyWithoutTarget<T>(interceptor);
	}

	public static T For<T>(string hostUrl)
		where T : class
	{
		var client = new HttpClient() { BaseAddress = new Uri(hostUrl) };
		return For<T>(client);
	}

	class RestMethodInterceptor<T> : IInterceptor
	{
		static readonly Dictionary<string, Func<HttpClient, object[], object>> methodImpls
			= typeof(T).GetMethods().Select(m => m.Name) //Refit 版本4+
			//RequestBuilder.ForType<T>().InterfaceHttpMethods //Refit 版本4-
				.ToDictionary(k => k, v => RequestBuilder.ForType<T>().BuildRestResultFuncForMethod(v));

		readonly HttpClient client;

		public RestMethodInterceptor(HttpClient client)
		{
			this.client = client;
		}

		public void Intercept(IInvocation invocation)
		{
			if (!methodImpls.ContainsKey(invocation.Method.Name))
			{
				throw new NotImplementedException();
			}
			invocation.ReturnValue = methodImpls[invocation.Method.Name](client, invocation.Arguments);
		}
	}
}
  1. 调用的地方改为使用代理类
1
2
--    var gitApi = RestService.For<IGitHubApi>(url);
++    var gitApi = ProxyRestService.For<IGitHubApi>(url);

原因

在linqpad中由于不支持source generator,而Refit需要通过source generator来生成代理接口的实现,造成不能使用


参考资料

本文会经常更新,请阅读原文: https://dashenxian.github.io/post/%E5%9C%A8linqpad%E7%8E%AF%E5%A2%83%E4%B8%AD%E4%BD%BF%E7%94%A8Refit ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

知识共享许可协议

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名 小神仙 (包含链接: https://dashenxian.github.io ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系 (125880321@qq.com)

登录 GitHub 账号进行评论