Castle IoC - 支持Release(...)的ISubDependencyResolver?

时间:2009-10-23 04:43:42

标签: c# castle-windsor ioc-container

是否可以构建像ISubDependencyResolver一样的东西,但也支持Release(...)?

我有一种情况,我希望能够在Blender的构造函数中解析派生类的Fruit:

abstract class Fruit
{
}

class AppleBlender
{
    AppleBlender(Apple a)
    {
    }
}
不幸的是,Apple在一个不同的程序集中,我不想在需要之前加载,因为有数百种不同的Fruit都有自己的程序集。

ISubDependencyResolver对此很有用,除了我的一些水果是一次性的,所以我需要一种方法让它们被释放。

是从DefaultDependencyResolver派生出来的唯一方法吗?

编辑:更全面的例子。

[TestFixture]
public class SubResolverFixture
{
    [Test]
    public void ResolvedInstanceShouldBeDisposed()
    {
        IKernel kernel = new DefaultKernel();
        kernel.Resolver.AddSubResolver(new TestResolver());

        kernel.Register(Component.For<AppleBlender>().LifeStyle.Transient);

        AppleBlender ab = kernel.Resolve<AppleBlender>();
        kernel.ReleaseComponent(ab);

        Assert.That(ab.IsDisposed);
        Assert.That(ab.Apple.IsDisposed);
    }
}

public class TestResolver : ISubDependencyResolver
{
    public object Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
    {
        return new Apple();
    }

    public bool CanResolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
    {
        return typeof(Fruit).IsAssignableFrom(dependency.TargetType);
    }
}

public abstract class Fruit : IDisposable
{
    public bool IsDisposed
    {
        get;
        set;
    }

    public void Dispose()
    {
        IsDisposed = true;
    }
}

public class Apple : Fruit
{
}

public class AppleBlender : IDisposable
{
    public AppleBlender(Apple apple)
    {
        Apple = apple;
    }

    public Apple Apple
    {
        get;
        set;
    }

    public bool IsDisposed
    {
        get;
        set;
    }

    public void Dispose()
    {
        IsDisposed = true;
    }
}

基本上我想要一种方法将“新Apple()”视为需要处理的瞬态对象。我很乐意在这个上采用完全不同的轨道,但是“Apple”类型需要在解决时间(而不是启动时间)加载。

1 个答案:

答案 0 :(得分:2)