2009-08-17 73 views
1

我使用Bojan Resnik在this question中描述的方法來解析未在Windsor容器中註冊的類的實例。問題是我不希望這些類作爲「服務」提供給其他已解決的實例。Castle IoC - 如何防止註冊組件被解析爲依賴關係?

例如,給出以下類:

class Order 
{ 
    public Order(ITaxCalculator tc) 
    { 
     // ... 
    } 
} 

class SomeOtherThing 
{ 
    public SomeOtherThing(ISomeOtherService sos) 
    { 
     // ... 
    } 

    Order CurrentOrder 
    { 
     get; 
     set; 
    } 
} 

static class WindsorExtensions 
{ 
    public static object Create(this IWindsorContainer container, Type type) 
    { 
     if (!type.IsClass) 
     { 
      throw new ArgumentException("not class", "type"); 
     } 

     if (!container.Kernel.HasComponent(type)) 
     { 
      container.Kernel.AddComponent(type.FullName, type, LifestyleType.Transient); 
     } 

     return container.Resolve(type); 
    } 

    public static T Create<T>(this IWindsorContainer container) 
    { 
     return (T)ResolveType(container, typeof(T)); 
    } 
} 

我希望能夠說:

Order order = container.Create<Order>(); 
SomeOtherThing thing = container.Create<SomeOtherThing>(); 

但我不想訂購的新實例獲得注入到SomeOtherThing的CurrentOrder屬性。基本上,我希望容器創建實例,以便可以注入依賴關係,但我不希望這些類可用於注入其他類。

爲了達到這個目標,我不介意爲容器寫額外的擴展名,只要有人能指出我正確的方向。

回答

0

默認情況下,windsor在屬性注入時使用構造函數注入。由於這個CurrentOrder永遠不會被注入SomeOtherThing類,除非將它添加到構造函數中。

看着你的代碼,你基本上遲到了將組件註冊到容器中。如果你想確定它從未被注入過,你可以在它解決了之後將它移除,例如。

static class WindsorExtensions 
{ 
public static object Create(this IWindsorContainer container, Type type) 
{ 
    if (!type.IsClass) 
    { 
     throw new ArgumentException("not class", "type"); 
    } 
    if (!container.Kernel.HasComponent(type)) 
    { 
     container.Kernel.AddComponent(type.FullName, type, LifestyleType.Transient); 
    } 
    object instance = container.Resolve(type); 
    container.Kernel.RemoveComponent(type.FullName); 
    return instance; 

} 

public static T Create<T>(this IWindsorContainer container) 
{ 
    return (T)ResolveType(container, typeof(T)); 
} 
} 
1

我覺得,因爲它使用了「未登記」成分的孩子內核this workaround將解決您的問題,所以它應該不會影響其他組件。

相關問題