越来越多.NET 核心库被绑定到IServiceCollection
。在示例中,我想在我的.NET Framework 4.7.1 中使用HttpClientFactory
描述这里。桌面应用。我的应用程序使用的是 Unity IoC。我引用了Microsoft.Extensions.Http
作为 NuGet。
但是有一个问题:新的 ASP.Net 核心组件绑定到 Microsoft DI 框架.NetCore - IServiceCollection
。例如,HttpClientFactory
的注册在这里:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
}
我正在深入MS 代码并希望手动向 Unity 注册相应的接口和类。这是 IServiceCollection 注册服务的方式:
services.TryAddTransient<HttpMessageHandlerBuilder, DefaultHttpMessageHandlerBuilder>();
services.TryAddSingleton<IHttpClientFactory, DefaultHttpClientFactory>();
将此移至 Unity IoC 是没有问题的,但是当我想注册具有内部可见性的DefaultHttpMessageHandlerBuilder
和DefaultHttpClientFactory
时,我被困住了。因此,它们不能在 MS 代码之外注册。
我有机会如何解决这种情况吗?
2 回答
你有 2 个选择:
创建一个 ServiceCollection,添加工厂,然后调用 BuildServiceProvider 并解析 IHttpClientFactory。这里有一个超级样本https://github.com/aspnet/HttpClientFactory/blob/64ed5889635b07b61923ed5fd9c8b69c997deac0/samples/HttpClientFactorySample/Program.cs#L21。
使用单位适配器
IServiceCollection
https://www.nuget.org/packages/Unity.Microsoft.DependencyInjection/。基于 on_3_answer,我使用了他的第二个解决方案并完成了代码:
这些包需要从我的项目中引用(来自.csproj 的片段):
以下是可以从 Unity 容器解析 ServiceCollection 服务的测试: