Reputation: 22595
When I configure a DbContext
with Autofac as "lifetime scope", then in the scope of a request that means that it is disposed of at the end of a request.
But what happens when we get a DbContext
from the container in the Application_Start()
method of an MVC application?
We have a settings class that is set up as a singleton:
builder.RegisterType<Settings>().As<ISettings>().SingleInstance();
And in Application_Start()
we get the settings from the container:
var settings = DependencyResolver.Current.GetService<ISettings>();
The Settings class is dependent on a DbContext
- and the DbContext
is set up in lifetime scope
We know that this is a captive dependency, but do not think that is an issue, because the class uses the context once only.
My concern is whether the DbContext
ever releases its resources.
In Application_Start()
are we in the scope of a request or are we in the scope of the application?
And if we are in the scope of the application does "lifetime scope" mean that we don't dispose of the DbContext
until the application stops?
Upvotes: 0
Views: 172
Reputation: 16192
Resources will be released one the scope disposed in your case it is the application scope so resources will be released when the application stopped.
In such a case I would use Func<Owned<DbContext>>
, something like that :
public class Settings
{
Settings(Func<Owned<DbContext>> contextFactory)
{
this._contextFactory = contextFactory;
}
private readonly Object _lock = new Object();
private readonly Func<Owned<DbContext>> _contextFactory;
private Boolean _isSettingsLoaded = true;
private Int32 _settingsA;
public Int32 SettingsA
{
get
{
this.EnsureSettingsLoaded();
return _settingsA;
}
}
private void EnsureSettingsLoaded()
{
if (!this._isSettingsLoaded)
{
lock (this._lock)
{
if (!this._isSettingsLoaded)
{
using (Owned<DbContext> context = this._contextFactory())
{
// context.Value.DoSomething();
}
this._isSettingsLoaded = true;
}
}
}
}
}
Upvotes: 1