container.RegisterWebAPIRequest<SimplePOCO>();
从APIController方法内部,我可以请求一个实例.到现在为止还挺好.我想将我的测试扩展到早期的管道,特别是消息处理程序.所以我创建了一个简单的DelegatingHandler,如:
protected overrIDe Task<httpResponseMessage> SendAsync( httpRequestMessage request,CancellationToken cancellationToken) { Task<httpResponseMessage> response; var container = SimpleInjectorWebAPIInitializer.container; var rc = container.GetInstance<SimplePOCO>(); response = base.SendAsync(request,cancellationToken); response.ContinueWith((responseMsg) => { }); return response;}
使用以下消息调用GetInstance< SimplePOCO>()错误:
The registered delegate for type SimplePOCO threw an exception. The
SimplePOCO is registered as ‘Web API Request’ lifestyle,but the
instance is requested outsIDe the context of a Web API Request.
难道我做错了什么?消息处理程序是否在WebAPI请求的生命周期之外?考虑到它们的完整性,这看起来很奇怪.如果消息处理程序在生命周期之外,那么包含消息处理程序的生命周期会更长吗?
解决方法Are Message Handlers outsIDe the lifetime of a WebAPI request?
嗯,事实上,他们是.除非您显式触发IDependencyScope的创建,否则将在DefaulthttpControllerActivator.Create方法内创建IDependencyScope(通过调用request.GetDependencyScope()).
要确保代码在依赖范围内运行,您所要做的就是在处理程序中显式调用request.GetDependencyScope():
protected overrIDe Task<httpResponseMessage> SendAsync( httpRequestMessage request,CancellationToken cancellationToken) { // trigger the creation of the scope. request.GetDependencyScope(); Task<httpResponseMessage> response; var container = SimpleInjectorWebAPIInitializer.container; var rc = container.GetInstance<SimplePOCO>(); response = base.SendAsync(request,cancellationToken); response.ContinueWith((responseMsg) => { }); return response;}总结
以上是内存溢出为你收集整理的c# – SimpleInjector的WebAPIRequest生命周期是否包含消息处理程序?全部内容,希望文章能够帮你解决c# – SimpleInjector的WebAPIRequest生命周期是否包含消息处理程序?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)