2

Unity2.0をIoCコンテナーとして使用するASP.NetMVC3Webアプリケーションを開発しています。

以下に、 Global.asaxファイルのApplication_Start()メソッドの例を示します。

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    IUnityContainer container = new UnityContainer();

    container.RegisterType<IControllerActivator, CustomControllerActivator>(
        new HttpContextLifetimeManager<IControllerActivator>());

    //container.RegisterType<IUnitOfWork, UnitOfWork>(
    //  new ContainerControlledLifetimeManager());
    container.RegisterType<IUnitOfWork, UnitOfWork>(
        new HttpContextLifetimeManager<IUnitOfWork>());

    container.RegisterType<IListService, ListService>(
        new HttpContextLifetimeManager<IListService>());
    container.RegisterType<IShiftService, ShiftService>(
        new HttpContextLifetimeManager<IShiftService>());

    DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}

私のHttpContextLifetimeManagerは次のようになります

public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable
{
    public override object GetValue()
    {
        return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];
    }

    public override void RemoveValue()
    {
        HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);
    }

    public override void SetValue(object newValue)
    {
        HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] =
            newValue;
    }

    public void Dispose()
    {
        RemoveValue();
    }
}

私の問題は、上記のクラスのメソッドDispose()は、ブレークポイントを設定したときに呼び出されないことです。IoCコンテナインスタンスが破棄されないのではないかと心配しています。これは問題につながる可能性がありますか?

Global.asaxファイルに配置したこのコードスニペットを見つけましたが、それでもDispose()メソッドが呼び出されることはありません

protected void Application_EndRequest(object sender, EventArgs e)
{
    using (DependencyResolver.Current as IDisposable);
}

Unityコンテナの各インスタンスを破棄する方法を教えてもらえますか?

ありがとう。

4

2 に答える 2

3

Unity.MVC3nugetパッケージを使用します。次に、初期化するときにHierarchicalLifetimeManagerを指定すると、各リクエストの後にオブジェクトが破棄されます。

container.RegisterType(new HierarchicalLifetimeManager());

それはそれと同じくらい簡単です:)

于 2012-07-26T16:40:25.410 に答える
2

Unityは、作成したインスタンスを追跡したり、それらを破棄したりしません。Rory Primroseには、追跡を実行し、を呼び出すことによってオブジェクトを破棄できるようにする拡張機能がありますcontainer.TearDown()

LifetimeManagersUnity vNextのウィッシュリストに追加された後、クリーンアップします。

新しいコンテナインスタンスのブートストラップは、すべてのリクエストで実行するとコストがかかります。したがって、すべての登録が完了したら、コンテナインスタンスをキャッシュすることを検討します。

于 2012-07-26T16:06:32.320 に答える