2009-10-23 50 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組件)

相關問題