.Net 6的Winform注入及使用WebApiClientCore
1、依赖:Microsoft.Extensions.DependencyInjection;
2、program.cs
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
var service = new ServiceCollection();
ConfigureServices(service);
var serviceProvider= service.BuildServiceProvider();
var form = serviceProvider.GetRequiredService<Form1>();
Application.Run(form);
}
/// <summary>
/// 注入服务
/// </summary>
/// <param name="services"></param>
public static void ConfigureServices(IServiceCollection services)
{
services.AddScoped<Form1>();
services.AddHttpApi<IXXX>();//注入的东西自己定义,这里是WebApiClientCore的
}
3、Form1.cs
public partial class Form1 : Form
{
IXXX api;
public Form1(IXXX api )
{
InitializeComponent();
this.api = api;
}
}
上面完成Winform的注入,
4、IXXX.cs定义
[HttpHost("https://api.xxx.com/APIService")]
public interface IXXX : IHttpApi
{
[HttpGet("/getR")]
Task<ApiResult> GetR(string keyword);
}
上面为api接口的定义