首页 > 解决方案 > StructureMap 异常代码:202 未为 PluginFamily System.Net.Http.HttpMessageHandler、System.Net.Http、版本 = 4.2.0.0 定义默认实例

问题描述

我有一个 WCF 应用程序,它正在侦听消息。EventHandler 使用 ServiceClient,它使用 HttpClient 调用另一个 API。

国际奥委会类:

public static class IoC
{
    public static IContainer Initialize()
    {
        ObjectFactory.Initialize(x =>
        {
            // Handlers
            x.For<IHandle>().Use<EventHandler>();

            // Service Clients
            x.For<HttpClient>().Use<HttpClient>();
            x.For<IServiceClient>().Use<ServiceClient>();
        });

        return ObjectFactory.Container;
    }
}

我尝试在 Initialize 之后但在返回之前添加它:

ObjectFactory.Configure(x =>
{
    x.Scan(scan =>
    {
        scan.LookForRegistries();
        scan.Assembly("System.Net.Http");
    });
});

但是,我仍然在标题中得到例外。

标签: c#wcfstructuremap

解决方案


I was able to resolve this issue. The problem was that I was using an older version of StructureMap (v2.6.4.1) which was not compatible with System.Net.Http, Version=4.2.0.0. After updating to the latest version and making some adjustments since ObjectFactory doesn't exist in the latest version, I was getting an error:

No default Instance is registered and cannot be automatically determined for type 'System.Net.Http.HttpMessageHandler'

This is because StructureMap defaultly tries to use the greediest constructor. To fix this, I changed my DI for HttpClient to this:

x.For<HttpClient>().Use<HttpClient>().SelectConstructor(() => new HttpClient());

推荐阅读