【发布时间】:2014-08-18 09:48:27
【问题描述】:
我用 Autofac 注册必要的类型为 InstancePerLifetimeScope:
builder.RegisterType<WebSecurityContext>()
.AsSelf()
.InstancePerLifetimeScope();
并通过接口解决:
builder.Register<IApplicationContext>(context =>
{
return context.Resolve<WebSecurityContext>();
})
.As<IApplicationContext>();
我在我的 WebAPI 控制器中注入 ApplicationContext:
public class MedicalCenterController : BaseApiController
{
private readonly IApplicationContext applicationContext;
public MedicalCenterController(IApplicationContext applicationContext)
{
this.applicationContext = applicationContext;
}
ApplicationContext 具有 MedicalCenterId 值。在 UI 上选择新的医疗中心后,此值应更改。
MedicalCenterId 的更改发生在还包含必要上下文的操作过滤器中。
public class MedicalCenterAttribute : ActionFilterAttribute
{
public IApplicationContext ApplicationContext
{
get;
set;
}
public override void OnActionExecuting(HttpActionContext filterContext)
{
.....
ApplicationContext.SetMedicalCenterId(medicalCenterId);
}
}
但在此之后,ApplicationContext 继续在 MedicalCenterController 和另一个控制器中保留以前的 MedicalCenterId 值。
虽然我使用 InstancePerLifetimeScope 对象,为什么 autofac 在不同的类中使用不同的实例?
谢谢。
【问题讨论】:
-
听起来您打算让
MedicalCenterId成为每个用户/会话关联的值。实际上并没有与此概念相关联的生命周期范围。如果是我,我会实现我的WebSecurityContext从当前的 HttpSession 中提取这个值。
标签: c# .net asp.net-mvc dependency-injection autofac