Hi,
I have a asp.net mvc web site where I make use of the Dependency Injections features of the "Micorosoft.Practices.Unity
" and "Microsoft.Practices.ObjectBuilder2
". This all works great by injected my objects into my controllers constructors.
The problem is that I am having difficulty in clearing this session when a user leaves the browser or wants to log off. All the values remain persisted in the objects. How can I destory the container which is created in the global.asax on either Session_End()
or by a user click and taken care by a controller action.
Below is some sample code.
Global.asax
- Performed from Session_start
:
protected static void RegisterDependencies()
{
IUnityContainer container = new UnityContainer();
container.RegisterType<DataStore, DataStore>(new SessionLifetimeManager<DataStore>());
container.RegisterType<IMotorRepository, MotorRepository>(new SessionLifetimeManager<IMotorRepository>());
container.RegisterType<ICoverRepository, CoverRepository>(new SessionLifetimeManager<ICoverRepository>());
container.RegisterType<IDriverRepository, DriverRepository>(new SessionLifetimeManager<IDriverRepository>());
container.RegisterType<IVehicleRepository, VehicleRepository>(new SessionLifetimeManager<IVehicleRepository>());
container.RegisterType<ICodeValueRepository, CodeValueRepository>(new SessionLifetimeManager<ICodeValueRepository>());
ControllerBuilder.Current.SetControllerFactory(
new UnityControllerFactory(container)
);
}
SessionLifeTimeManager
:
public class SessionLifetimeManager<T> : LifetimeManager, IDisposable
{
public override object GetValue()
{
return HttpContext.Current.Session[typeof(T).AssemblyQualifiedName];
}
public override void RemoveValue()
{
HttpContext.Current.Session.Remove(typeof(T).AssemblyQualifiedName);
}
public override void SetValue(object newValue)
{
HttpContext.Current.Session[typeof(T).AssemblyQualifiedName] = newValue;
}
public void Dispose()
{
RemoveValue();
}
}