越来越多的.NET Core库绑定到IServiceCollection
。在示例中,我想在我的.NET Framework 4.7.1中使用HttpClientFactory
描述here。桌面应用。我的应用程序使用的是Unity IoC。我将Microsoft.Extensions.Http
称为NuGet。
但是存在一个问题:新的ASP.Net Core组件绑定到.NetCore的Microsoft DI框架 - IServiceCollection
。例如,HttpClientFactory
的注册位于:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
}
我正在深入MS code并希望手动向Unity注册相应的接口和类。这是IServiceCollection注册服务的方式:
services.TryAddTransient<HttpMessageHandlerBuilder, DefaultHttpMessageHandlerBuilder>();
services.TryAddSingleton<IHttpClientFactory, DefaultHttpClientFactory>();
将此移至Unity IoC是没有问题的,但当我想注册具有内部可见性的DefaultHttpMessageHandlerBuilder
和DefaultHttpClientFactory
时,我感到困惑。因此,它们不能在MS代码之外注册。
我有机会如何解决这种情况吗?
答案 0 :(得分:4)
您有两个选择:
创建一个ServiceCollection,添加工厂,然后调用BuildServiceProvider并解析IHttpClientFactory。这里有一个超级样本https://github.com/aspnet/HttpClientFactory/blob/64ed5889635b07b61923ed5fd9c8b69c997deac0/samples/HttpClientFactorySample/Program.cs#L21。
对IServiceCollection
https://www.nuget.org/packages/Unity.Microsoft.DependencyInjection/使用单位适配器。
答案 1 :(得分:4)
基于@davidfowl答案,我使用了他的第二个解决方案并完成了代码:
这些包需要从我的项目中引用(.csproj的片段):
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Http">
<Version>2.1.1</Version>
</PackageReference>
<PackageReference Include="Unity.Microsoft.DependencyInjection">
<Version>2.0.10</Version>
</PackageReference>
</ItemGroup>
这是可以从Unity容器解析ServiceCollection服务的测试:
using System;
using System.Linq;
using System.Net.Http;
using Microsoft.Extensions.DependencyInjection;
using Unity;
using Unity.Microsoft.DependencyInjection;
using Xunit;
namespace FunctionalTests
{
public class UnityWithHttpClientFactoryTest
{
/// <summary>
/// Integration of Unity container with MS ServiceCollection test
/// </summary>
[Fact]
public void HttpClientCanBeCreatedByUnity()
{
UnityContainer unityContainer = new UnityContainer();
ServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddHttpClient("Google", (c) =>
{
c.BaseAddress = new Uri("https://google.com/");
});
serviceCollection.BuildServiceProvider(unityContainer);
Assert.True(unityContainer.IsRegistered<IHttpClientFactory>());
IHttpClientFactory clientFactory = unityContainer.Resolve<IHttpClientFactory>();
HttpClient httpClient = clientFactory.CreateClient("Google");
Assert.NotNull(httpClient);
Assert.Equal("https://google.com/", httpClient.BaseAddress.ToString());
}
}
}