私は、 "Micorosoft.Practices.Unity
"と "Microsoft.Practices.ObjectBuilder2
"のDependency Injections機能を利用するasp.net mvc Webサイトを持っています。これはすべて私のオブジェクトを私のコントローラのコンストラクタに挿入することで素晴らしいものです。UnityContainerセッション状態でのASP.NET MVC依存性注入
問題は、ユーザーがブラウザを離れたりログオフしたりするときにこのセッションをクリアするのが難しいことです。すべての値はオブジェクト内に保持されたままです。どのようにしてSession_End()
のglobal.asaxで作成されたコンテナをデリートするか、ユーザーがクリックしてコントローラの操作で気を配ります。
以下はいくつかのサンプルコードです。
Global.asax
から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();
}
}
おそらく私は間違っていますが、あなたはセッションごとのコンテナを持っているように、あなたがしていることを恐ろしいように見せています。まず、「SetControllerFactory」を別の場所で呼び出すロジックがない限り、 SetControllerFactoryは、セッション全体ではなく、アプリケーション全体のコントローラファクトリを設定するため、怪我のために準備する必要があります。 – meandmycode