2009-10-23 48 views
2

是否有可能构建像ISubDependencyResolver一样的工作,但也支持Release(...)?Castle IoC - 支持Release(...)的ISubDependencyResolver?

我有,我希望能够解决在搅拌机的构造函数派生类水果的情况:

abstract class Fruit 
{ 
} 

class AppleBlender 
{ 
    AppleBlender(Apple a) 
    { 
    } 
} 

苹果是不幸的是在不同的组件,我不希望加载直到需要,因为有数百种不同种类的水果都有自己的组装。

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”。

+0

那岂不是开箱注册这个开箱即用的组件? MicroKernel具有IReleasePolicy接口,可以实现这一点,并在您释放组件后处置您的依赖关系。 你可以发布更完整的样本吗?我真的不明白你的想法...... – 2009-10-23 08:06:48

+0

好的,我会聚集一个更完整的样本,它可能需要等到星期一。这似乎是因为Apple从子依赖解析器返回,所以它不会被丢弃。 – 2009-10-23 08:53:44

+0

星期一之前得到它:) – 2009-10-23 09:10:50

回答

2

温莎2.5支持通过UsingFactoryMethod(或者更广泛地说对具有执行类型设置为LateBoundComponent组件)

相关问题