gpt4 book ai didi

asp.net - CaSTLe Windsor 3 跨多个 Web 请求持久化 PerWebRequest 对象

转载 作者:行者123 更新时间:2023-12-01 11:00:11 25 4
gpt4 key购买 nike

我有一个 MVC 4 项目,正在尝试将一个 PerWebRequest 对象注入(inject)到我的 Controller 中。然而,对象似乎没有在多个请求中重新创建

 private static IWindsorContainer InitializeWindsor()
{
var container = new WindsorContainer().Install(FromAssembly.This());

// Add Factory facility
container.AddFacility<TypedFactoryFacility>();

// Register all controllers from this assembly
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
container.Register(
AllTypes.FromAssembly(assembly).BasedOn<Controller>().Configure(c => c.LifestyleTransient())
);
}

// Register HTTP Handlers
container.Register(Component.For<HttpRequestBase>().LifeStyle.PerWebRequest.UsingFactoryMethod(() => new HttpRequestWrapper(HttpContext.Current.Request)));
container.Register(Component.For<HttpContextBase>().LifeStyle.PerWebRequest.UsingFactoryMethod(() => new HttpContextWrapper(HttpContext.Current)));


// Register components
container.Register(Component.For<PerWebRequestObject>().LifeStyle.PerWebRequest);
}

这是我的 PerWebRequestObject:

public class PerWebRequestObject
{
public DateTime DateCreated { get; set; }

public PerWebRequestObject()
{
DateCreated = DateTime.UtcNow;
Debug.WriteLine("Created: " + DateCreated.ToLongTimeString());
}
}

这是我的测试 Controller :

public class TestController : BaseController
{
public PerWebRequestObject pwrObject { get; set; }

public ActionResult Test()
{
Debug.WriteLine(pwrObject.DateCreated.ToLongTimeString());
return new ContentResult();
}
}

为什么这不起作用?请注意,我正在使用 WindsorControllerFactory 并像这样释放 Controller :

    public override void ReleaseController(IController controller)
{
var disposableController = controller as IDisposable;
if (disposableController != null)
disposableController.Dispose();

_windsorContainer.Release(controller);
}

最佳答案

两件事:

  • 您怎么知道对象的生命周期不正确(没有跨网络请求重新创建)?

一个可能的解释是你的依赖看起来像这样:

Controller --> 单例 --> 你的 per-web-request-component

这是生活方式的不匹配,这可以解释您所看到的行为

  • 不要丢弃 Controller 。这是容器的工作。

关于asp.net - CaSTLe Windsor 3 跨多个 Web 请求持久化 PerWebRequest 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11775346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com