C# Castle Windsor:如何检测具有比依赖项更长生存期的注册?

C# Castle Windsor:如何检测具有比依赖项更长生存期的注册?,c#,.net,dependency-injection,castle-windsor,C#,.net,Dependency Injection,Castle Windsor,我发现,在CastleWindsor DI中,您可以很容易地了解到一种情况,即使用不同生活方式注册的依赖组件 假设我们有以下类和接口: public class MyThing : IMyThing { public MyThing() { } } public interface IMyThing {} 这已在相关Windsor安装程序中注册,其中还包括HttpContextBase的注册: container.Register( Component

我发现,在CastleWindsor DI中,您可以很容易地了解到一种情况,即使用不同生活方式注册的依赖组件

假设我们有以下类和接口:

public class MyThing : IMyThing
{
    public MyThing()
    {
    }
}

public interface IMyThing {}
这已在相关Windsor安装程序中注册,其中还包括HttpContextBase的注册:

container.Register(
    Component
    .For<IMyThing>()
    .ImplementedBy<MyThing>()
    .LifeStyle.Singleton);

container.Register(
    Component
    .For<HttpContextBase>()
    .UsingFactoryMethod(_ => new HttpContextWrapper (HttpContext.Current) )
    .LifestylePerWebRequest());
public class MyThing : IMyThing
{
    private readonly HttpContextBase _httpContext;

    public MyThing(HttpContextBase httpContext)
    {
        _httpContext = httpContext;
    }
}
从表面上看,这似乎相当合理——毕竟,在设计类时,您应该能够做到这一点,而不必考虑依赖注入的细节。然而,在现实中,我们现在有一个微妙的(但可能很严重的)缺陷,即一个组件依赖于另一个组件,而另一个组件的生活方式比它本身要短

我本以为这会给温莎城堡带来某种例外,但似乎不会。它将很好地为您提供一个关于当时当前HttpContext的神话,并将在应用程序的剩余生命周期中继续使用相同的HttpContext提供相同的对象


在谷歌搜索了一段时间后,我还没有找到任何与这个问题相关的温莎配置。有人对此有什么建议吗?我所从事的项目有一个绝对的DI设置的狗餐,并且发现这类问题被证明是非常困难的(在我给出的示例中,如果控制器具有错误的HttpContext,这应该是非常明显的,但在其他情况下可能会少很多).

Castle Windsor不会为此引发异常,但会在调试器中将其显示为警告。(在新选项卡中打开图像)

下面是一个可以显示它的测试:

[TestFixture]
public class WindsorTests
{
    [Test]
    public void LifecycleWarningTest()
    {
        IWindsorContainer container = new WindsorContainer();
        container.Register(
                Component.For<ISingleton>().ImplementedBy<Singleton>().LifestyleSingleton(),
                Component.For<ITransient>().ImplementedBy<Transient>().LifestyleTransient()
            );

        ISingleton singleton = container.Resolve<ISingleton>();

    }

}


interface ISingleton
{

}

class Singleton : ISingleton
{
    private readonly ITransient _transient;

    public Singleton(ITransient transient)
    {
        _transient = transient;
    }
}

interface ITransient
{

}

class Transient : ITransient
{
}
[TestFixture]
公共级WindsorTests
{
[测试]
公共无效生命周期警告测试()
{
IWindsorContainer=新WindsorContainer();
集装箱。登记(
Component.For().ImplementedBy().LifestyleSingleton(),
Component.For().ImplementedBy().LifestyleTransient()实现
);
ISingleton singleton=container.Resolve();
}
}
界面伊辛格尔顿
{
}
单件类:ISingleton
{
私有只读ITransient\u transient;
公共单例(ITransient transient)
{
_瞬态=瞬态;
}
}
接口ITransient
{
}
类瞬态:ITransient
{
}

是的,那么我们可以写一个简单的检查“潜在生活方式不匹配”系列中的任何项目吗?我找不到它在哪里。你可能想检查一下源代码;这些集合似乎仅对调试器可用,并且无法在代码中访问:(