我正在研究在以前使用Castle Windsor的Web应用程序中使用Autofac。Autofac会话范围
我真正喜欢Autofac的东西是能够通过lamda表达式来表达动态组件构造,而不是在Windsor中创建DependancyResolvers等。
我有一个场景是我想要一个特定的组件在ASP.NET会话级作用域注册。随着温莎我会创建/源的新LifestyleManager,但与Autofac我想出了这一点:
//Register SessionContext at HTTP Session Level
builder.Register(c =>
{
HttpContext current = HttpContext.Current;
//HttpContext handes delivering the correct session
Pelagon.Violet.Core.Interfaces.SessionContext instance = current.Session["SessionContext"] as Pelagon.Violet.Core.Interfaces.SessionContext;
if (instance == null)
{
instance = c.Resolve<Pelagon.Violet.Core.Interfaces.SessionContext>();
current.Session["SessionContext"] = instance;
}
return instance;
})
.FactoryScoped();
这在某些时候我也许能变成一个扩展方法。如果HttpContext.Current.Session为空,我接受此实现将会弹出,因为它只应用于Web应用程序。
的问题是:
哪些是Autofac这种注册的最佳实践。我已经看到很多关于使用嵌套容器等的提及,但没有具体的例子,并且我很想了解上述方法可能会出现什么问题(只有我能想到的是自动处理的东西)。
谢谢。
嗨,尼克。感谢您的反馈,关于使用嵌套容器管理Web应用程序中的作用域,您是否知道任何具体示例,即Global.asx文件,这些文件将显示每个容器的构建和“使用”位置?无法在文档中看到它。 – crowleym 2009-09-10 09:06:17
不确定它是100%最新的,但这应该有所帮助:http://code.google.com/p/autofac/source/browse/branches/1.4/src/Example/Remember.Web/Global。 asax.cs – 2009-09-11 01:32:14