我有一个MVC 4项目,我正在尝试将PerWebRequest对象注入我的控制器。但是,似乎没有跨多个请求重新创建对象
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());
}
}
这是我的TestController:
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);
}
答案 0 :(得分:5)
两件事:
一种可能的解释是您的依赖关系如下所示:
控制器 - &gt;单身人士 - &gt;您的每个网络请求组件
这是一种生活方式不匹配,这可以解释你正在做的行为
答案 1 :(得分:1)
升级到Castle Windsor v3.1为我们解决了这个问题,无需更改任何代码。
我认为Windsor v3.0 + MVC 4的组合肯定存在问题。