c# - IServiceProvider garbage collection / disposal -


i trying debug memory leak in app (see related question) , have encountered smilingly wrong behavior.

in code (simplified snippet, of course):

    while (true)     {         using (var context = _serviceprovider.getrequiredservice<idatacontext>())         {             console.writeline("hello");         }     } 

memory consumption grows rapidly.

if comment out service spawn, memory consumption stable.

    while (true)     {         // using (var context = _serviceprovider.getrequiredservice<idatacontext>())         // {             console.writeline("hello");         // }     } 

service registered transient.

my understanding using statement responsible disposing service. var context created in scope of while , should destroyed when new iteration begins.

my first thought gc not job enough, not frequency increase when amount of consumed memory increases?

why wrong?

after days of fighting problem, derived answer. in short, issue microsoft di container does not dispose transient services, keeps references on them.

here corresponding issue on github.

the developers not plan fix since cost (complexity , hackiness) of fixing overweighs benefits.

suggested workaround using scoped service instead of transient one.

here example code, see more in issue.

using (var scope = serviceprovider.createscope()) using (var context = scope.serviceprovider.getrequiredservice<idatacontext>()) { ... } 

Comments