简体   繁体   English

Castle Windsor处理订单

[英]Castle Windsor dispose order

I have a problem with dispose order of resolved components using Windsor Castle. 我使用Windsor Castle处理已解析组件的处理顺序有问题。 The issue can be demonstrated on the following code 可以通过以下代码演示此问题

class Program
{
    static void Main(string[] args)
    {
        using (WindsorContainer container = new WindsorContainer())
        {
            container.Register(Component.For<C1>().LifestyleSingleton());
            container.Register(Component.For<C2>().LifestyleTransient());
            C1 c1 = container.Resolve<C1>();
            container.Release(c1);
            Console.WriteLine("Release done");
        }
        Console.WriteLine("Container dispose done");
    }
}

public class C1 : IDisposable
{
    private C2 m_c2;

    public C1(C2 c2)
    {
        m_c2 = c2;
    }

    public void Dispose()
    {
        Console.WriteLine("Dispose C1");
    }
}

public class C2 : IDisposable
{
    public void Dispose()
    {
        Console.WriteLine("Dispose C2");
    }
}

It prints out following: 它打印出以下内容:

Release done
Dispose C2
Dispose C1
Dispose C2
Container dispose done

I would expect following output: 我希望以下输出:

Release done
Dispose C1
Dispose C2
Container dispose done

Disposing C2 before C1 can cause serious problem in C1. 在C1之前处理C2会导致C1出现严重问题。 C1 can still be alive and be processing something. C1仍然可以存活并处理某些事情。 Note that problem disappears when both components are registered with LifestyleSingleton or LifestyleTransient but there still exist cases where registering C2 as LifestyleTransient can be useful. 请注意,当两个组件都注册了LifestyleSingleton或LifestyleTransient时,问题就会消失,但仍然存在将C2注册为LifestyleTransient可能有用的情况。

Is there a way to register or resolve components to solve this problem? 有没有办法注册或解决组件来解决这个问题?

I solved this issue by using a scope and register C1 as Scoped. 我通过使用范围并将C1寄存为Scoped来解决了这个问题。 In this case, the dispose order is correct. 在这种情况下,处置订单是正确的。 But I'm not sure if this is the recommended way. 但我不确定这是否是推荐的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM