c# - Autofac resolving a singleton creates a bottleneck -


i'm using autofac in asp.net mvc app , came across problem locking. anytime service depends on singleton, service resolved root lifetime scope. because autofac:

  • resolves singleton components root scope
  • resolves components root scope have dependencies must resolved root.

further, when resolving scope, autofac locks scope. think these fine design decisions. problem misbehaving classes depend on singletons and have slow constructors. these create bottleneck else needing resolve singleton.

since in mvc app, each request getting mapped mvc controller that's constructor injected. further, of controllers take dependencies on various singleton services (logging, caching, etc).

for things fast constructors not problem. 1 poorly written class requested, throughput tanks because every new request blocked on misbehaving constructor. example:

given these 3 classes

//registered singleinstance() class mysingleton {}  class badtransient {     public badtransient(mysingleton s)     { thread.sleep(5000); } }    class friendlytransient {} 

resolved like

using(var scope = container.beginlifetimescope("nested scope")) {      //resolves child scope     var myfriend = scope.resolve<friendlytransient>();       //resolves root because it's singleton     var singleton = scope.resolve<mysingleton>();       //resolves root because has singleton dependency.      //**** locks root scope 5 seconds     //****   no 1 else can resolve singletons.     var troublemaker = scope.resolve<badtransient>();          } 

is there way can avoid bottleneck?

the obvious answer have fast constructors. reality not constructors in codebase can guaranteed fast. there's a lot of legacy code, there's lots of code relies on 3rd party code, there's code looks fast depends on code isn't, there's code that's fast breaks down in odd circumstances, etc. educating developers works extent.

we've been fixing constructors find them, need more proactive solution. it's not acceptable let users qa.

note: don't care slow constructors don't depend on singleton. lock lifetime scope, won't block other threads

i agree @nemesv object construction should fast, means not initializing in onactivated. rather, should lazily when component first used. instance implementing proxy or lazy<t> internally.

but if have application rather extreme throughput , concurrency characteristics , verified through performance profiling locking bottleneck, consider switching lock-free ioc container.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -