我正在使用Castle WCF Facility来使用以下配置初始化客户端代理:
<component
id="ComponentID"
type="SomeType, SomeType"
wcfEndpointConfiguration="WCFConfig"
lifestyle="PerWebRequest" >
</component>
我遇到的问题是,在现场我最终会遇到大量内存泄漏。用内存分析器分析了这个,我似乎在内存中留下了大量的WCF通道。我是否正确期望城堡WCF设施在网络请求结束时清理它?
答案 0 :(得分:0)
如果您使用生活方式perwebrequest,您需要确保在整个请求中不重新创建HttpContext。如果是,则需要传递HttpContext.Items,因为Castle http模块使用它来跟踪组件。
e.g。
改变了这个:
public CapturedViewResult Capture(ControllerContext controllerContext, Func<ActionResult> action)
{
CapturedViewResult capturedViewResult = new CapturedViewResult();
HttpContext currentContext = HttpContext.Current;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
HttpResponse response = new HttpResponse(stringWriter);
HttpContext context = new HttpContext(currentContext.Request, response) { User = currentContext.User };
context.Items["LocalizationContext"] = currentContext.Items["LocalizationContext"];
HttpContext.Current = context;
ViewResult result = action.Invoke() as ViewResult;
if (result != null)
{
capturedViewResult.ViewName = result.ViewName;
result.ExecuteResult(controllerContext);
}
else
{
throw new ArgumentException("Supplied controller action method did not return a ViewResult", "action");
}
HttpContext.Current = currentContext;
capturedViewResult.CapturedHtml = stringWriter.ToString();
}
return capturedViewResult;
}
对此:
public CapturedViewResult Capture(ControllerContext controllerContext, Func<ActionResult> action)
{
var capturedViewResult = new CapturedViewResult();
var currentContext = HttpContext.Current;
using (var stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
var response = new HttpResponse(stringWriter);
var context = new HttpContext(currentContext.Request, response) { User = currentContext.User };
foreach (var key in currentContext.Items.Keys)
{
context.Items.Add(key, currentContext.Items[key]);
}
HttpContext.Current = context;
var result = action.Invoke() as ViewResult;
if (result != null)
{
capturedViewResult.ViewName = result.ViewName;
result.ExecuteResult(controllerContext);
}
else
{
throw new ArgumentException("Supplied controller action method did not return a ViewResult", "action");
}
foreach (var key in context.Items.Keys)
{
currentContext.Items[key] = context.Items[key];
}
HttpContext.Current = currentContext;
capturedViewResult.CapturedHtml = stringWriter.ToString();
}
return capturedViewResult;
}