Reputation: 6962
I register necessary type with Autofac as InstancePerLifetimeScope:
builder.RegisterType<WebSecurityContext>()
.AsSelf()
.InstancePerLifetimeScope();
and resolve it through interface:
builder.Register<IApplicationContext>(context =>
{
return context.Resolve<WebSecurityContext>();
})
.As<IApplicationContext>();
I inject ApplicationContext in my WebAPI controller:
public class MedicalCenterController : BaseApiController
{
private readonly IApplicationContext applicationContext;
public MedicalCenterController(IApplicationContext applicationContext)
{
this.applicationContext = applicationContext;
}
ApplicationContext has MedicalCenterId value. This value should change after select of new medical center on UI.
Changing of the MedicalCenterId occurs in the action filter which also contains the necessary context.
public class MedicalCenterAttribute : ActionFilterAttribute
{
public IApplicationContext ApplicationContext
{
get;
set;
}
public override void OnActionExecuting(HttpActionContext filterContext)
{
.....
ApplicationContext.SetMedicalCenterId(medicalCenterId);
}
}
But after it, ApplicationContext continues to have previous value of MedicalCenterId in MedicalCenterController and another controllers.
Why autofac uses different instances in different classes, though I use InstancePerLifetimeScope object?
Thanks.
Upvotes: 1
Views: 1963
Reputation: 33930
Do not confuse lifetime scopes with singletons. Instances with lifetime scope will behave similar to singletons, but only within each lifetime scope. Thus, depending services resolved from a lifetime scope will get the same instance, but services resolved in another lifetime scope will get a different instance.
So, with Autofac in ASP.NET, in addition to the global/root lifetime scope shared by the whole application, each request gets a new lifetime scope. Since the application context in your case is registered with lifetime scope, on each request a new application context is created. The changes made to one instance is only seen by services within the same lifetime scope, and will be lost as soon as the request is done.
So, do not confuse lifetime scopes with singletons. A singleton must be registered with SingleInstance, not InstancePerLifetimeScope.
Update: since you are looking for a way to set "medical center id" per user, this is something you should not handle inside Autofac. My advice is to have ApplicationContext
load/store that value in some user-specific store. That way, whenever you query MedicalCenterId
it will be served per user, independent on how you register ApplicationContext
in your container.
Upvotes: 3