项目中需要经常请求API,请求次数越频繁时,由于是瞬态,系统响应变慢,故记录一下
参照
WPF Prism8.0中注册Nlog日志服务 - 痕迹g - 博客园 ,痕迹大佬使用5.0库实现Logger
包安装
DryIoc.Microsoft.DependencyIn6.2.0
Microsoft.Extensions.DependencyInjection9.0.4
重写IContainerExtension 方法
protected override IContainerExtension CreateContainerExtension()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddHttpClient();
return new DryIocContainerExtension(
new Container(CreateContainerRules()).WithDependencyInjectionAdapter(
serviceCollection
)
);
}
如果是5.0的DryIoc.Microsoft.DependencyIn则不需要重写CreateContainerRules
6.2.0需要重写
protected override Rules CreateContainerRules() { return Rules .Default.WithConcreteTypeDynamicRegistrations(reuse: Reuse.Transient) .With(Made.Of(FactoryMethod.ConstructorWithResolvableArguments)) .WithFuncAndLazyWithoutRegistration() .WithTrackingDisposableTransients() .WithFactorySelector(Rules.SelectLastRegisteredFactory()); }
在MainViewModel使用
//ctor
public MainViewModel(
IRegionManager regionManager,
IHttpClientFactory httpClientFactor,
IContainer container
)
{
var client = httpClientFactor.CreateClient();
Get(client);
}
//Get请求测试
public async void Get(HttpClient client)
{
try
{
CancellationTokenSource cts = new CancellationTokenSource(
TimeSpan.FromSeconds(100)
);
var data = await client.GetAsync(
"http://192.168.110.176:5000/api/GetToken/test",
cts.Token
);
Debug.WriteLine(data);
}
catch (OperationCanceledException ex)
{
Debug.WriteLine(ex.Message);
}
catch (Exception ex)
{
throw;
}
}