尝试在StructureMap ala中定义HttpClient单例:
For<HttpClient>().Singleton().UseIfNone<HttpClient>();
这会导致运行时出现以下错误(依赖项注入时):
StructureMap.StructureMapConfigurationException: No default Instance is registered and cannot be automatically determined for type 'System.Net.Http.HttpMessageHandler'
There is no configuration specified for System.Net.Http.HttpMessageHandler
1.) new HttpClient(*Default of HttpMessageHandler*)
2.) System.Net.Http.HttpClient
3.) Instance of System.Net.Http.HttpClient
4.) new AdmanAdapter(*Default of HttpClient*)
5.) Organotiki.vNext.PostEval.Data.Adapters.ADMAN.AdmanAdapter
6.) Instance of [....]
at lambda_method(Closure , IBuildSession , IContext )
at StructureMap.Building.BuildPlan.Build(IBuildSession session, IContext context)
at StructureMap.BuildSession.BuildNewInSession(Type pluginType, Instance instance)
at StructureMap.Pipeline.NulloTransientCache.Get(Type pluginType, Instance instance, IBuildSession session)
at StructureMap.BuildSession.ResolveFromLifecycle(Type pluginType, Instance instance)
at StructureMap.SessionCache.GetObject(Type pluginType, Instance instance, ILifecycle lifecycle)
如果我们还像这样配置HttpMessageHandler:
For<HttpClient>().Singleton().UseIfNone<HttpClient>();
For<HttpMessageHandler>().UseIfNone(x => new HttpClientHandler());
然后问题解决了。问题是为什么? HttpClient的默认构造函数负责其自己的依赖项注入:
/// <summary>Initializes a new instance of the <see cref="T:System.Net.Http.HttpClient" /> class.</summary>
[__DynamicallyInvokable]
public HttpClient()
: this((HttpMessageHandler) new HttpClientHandler())
{
}
我在这里想念东西吗?
答案 0 :(得分:2)
摘自documentation上的structuremap文档
如果一个混凝土上有多个公共构造函数 类,StructureMap的默认行为是选择“最贪婪” 构造函数,即参数最多的构造函数。
如果您查看HttpClient
的可能构造函数,则应该为
public HttpClient();
public HttpClient(HttpMessageHandler handler);
public HttpClient(HttpMessageHandler handler, bool disposeHandler);
答案 1 :(得分:1)
扩展@Brad M的答案,对我有用的是.SelectConstructor(() => new HttpClient())
。指定应显式使用哪个构造函数。