c# - Autofac - injected instance doesn't work as singleton -


i register necessary type autofac instanceperlifetimescope:

builder.registertype<websecuritycontext>()                 .asself()                 .instanceperlifetimescope(); 

and resolve through interface:

builder.register<iapplicationcontext>(context =>             {                 return context.resolve<websecuritycontext>();             })             .as<iapplicationcontext>(); 

i inject applicationcontext in webapi controller:

public class medicalcentercontroller : baseapicontroller {     private readonly iapplicationcontext applicationcontext;      public medicalcentercontroller(iapplicationcontext applicationcontext)     {         this.applicationcontext = applicationcontext;     } 

applicationcontext has medicalcenterid value. value should change after select of new medical center on ui.

changing of medicalcenterid occurs in action filter contains 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 have previous value of medicalcenterid in medicalcentercontroller , controllers.

why autofac uses different instances in different classes, though use instanceperlifetimescope object?

thanks.

do not confuse lifetime scopes singletons. instances lifetime scope behave similar singletons, within each lifetime scope. thus, depending services resolved lifetime scope same instance, services resolved in lifetime scope different instance.

so, autofac in asp.net, in addition global/root lifetime scope shared whole application, each request gets new lifetime scope. since application context in case registered lifetime scope, on each request new application context created. changes made 1 instance seen services within same lifetime scope, , lost request done.

so, not confuse lifetime scopes singletons. singleton must registered singleinstance, not instanceperlifetimescope.

update: since looking way set "medical center id" per user, should not handle inside autofac. advice have applicationcontext load/store value in user-specific store. way, whenever query medicalcenterid served per user, independent on how register applicationcontext in container.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -