Reputation: 7977
I have an ASP.NET web application with the following classes:
public class AppContext : IAppContext {
private readonly IDataContext _dataContext;
public AppContext(IDataContext dataContext) {
_dataContext = dataContext;
}
...
}
public class DataContext : IDataContext {
...
}
These are registered using Untity like so:
container.RegisterType<IAppContext, AppContext>(new ContainerControlledLifetimeManager());
container.RegisterType<IDataContext, DataContext>(new PerRequestLifetimeManager());
The AppContext is a singleton and lives for the lifetime of the application, but the DataContext only lives for the lifetime of the current request.
However since the DataContext is injected within the constructor of the AppContext class it will be persisted across requests. This causes issues issues as the DataContext is disposed after the request has ended. How could I inject the DataContext within the AppContext class so that I can retrieve the correct instance?
Upvotes: 1
Views: 567
Reputation: 7526
That means entire design of AppContext is invalid and it should live per request as it is now depends on some actual request data context.
As solution, split it up into singleton class which will contain shared logic, and class with logic which depends on data context AND shared logic.
public class SingletonAppContext : ISingletonAppContext //as singleton
{
//Source code where no data context needed
}
public class RequestAppContext : IRequestAppContext
{
public RequestAppContext(ISingletonAppContext appContext, IDataContext dataContext)
{
}
//Source code where data context is needed
}
Upvotes: 2