使用Unity而不是ASP.Net Core DI IServiceCollection

时间:2018-06-05 17:28:53

标签: c# asp.net-core dependency-injection unity-container

越来越多的.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是没有问题的,但当我想注册具有内部可见性的DefaultHttpMessageHandlerBuilderDefaultHttpClientFactory时,我感到困惑。因此,它们不能在MS代码之外注册。

我有机会如何解决这种情况吗?

2 个答案:

答案 0 :(得分:4)

您有两个选择:

答案 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());

        }

    }
}