6

我看着這個和它的一半回答我的問題:溫莎城堡內部構造函數/類

Castle Windsor: Register class with internal constructor?

但是你可以用溫莎使用內部的構造函數/類依賴注入一起? (所以構造函數參數也被注入)?我想保持內部的類/構造器允許最佳封裝(這些類不應暴露給公衆)。

我需要這種支持Silverlight的,所以我不認爲這是一個選項:

Castle Windsor: How to register internal implementations

感謝。

+0

恕我直言,這不是最佳封裝。如果你需要Windsor來訪問這些類,那麼它們沒有被恰當地封裝。寫一個門面或讓它們公開。 – 2010-10-26 13:33:56

+1

我不確定我是否理解。我有一個服務公共接口IMyService。我不希望該服務的消費者看到該實現。所以我有實現內部類MyService:IMyService。這種情況如何不代表最佳封裝? – Jeff 2010-10-26 14:44:29

+0

你讓內部類型與接口混淆。這些是正交的問題。 – 2010-10-26 19:40:39

回答

6

這可能不是一個令人滿意的答案,但最好的做法是讓所有需要使用公共構造函數通過Castle public實例化的類。你的設計應該允許一個下游依賴來實例化你的對象而不依賴Castle或InternalsVisibleTo。

對於你的問題,Castle只會搜索公共構造函數來實例化一個對象。我不相信有一種方法可以讓它搜索內部或私人構造函數。但是,如果你的類是內部的,你可以在不改變封裝的情況下公開你的內部構造函數。請參閱以下測試用例:

[TestFixture] 
public class InternalConstructorTests 
{ 
    [Test] 
    public void Test() 
    { 
     using (var container = new WindsorContainer()) 
     { 
      container.Register(
       Component.For<IFoo>().ImplementedBy<Foo>(), 
       Component.For<IBar>().ImplementedBy<Bar>(), 
       Component.For<IBaz>().ImplementedBy<Baz>() 
       ); 
      // fails because Castle can't find, and won't call, the internal constructor 
      Assert.Throws<ComponentActivatorException>(()=>container.Resolve<IFoo>()); 
      // passes because the Baz constructor is public, but the "real" encapsulation 
      // level is the same because the class is internal, effectively making the 
      // public constructor internal as well 
      container.Resolve<IBaz>(); 
     } 
    } 
} 
internal interface IBar{} 
internal class Bar : IBar{} 
internal interface IFoo{} 
internal class Foo : IFoo 
{ 
    internal Foo(IBar bar) 
    { 
    } 
} 
internal interface IBaz { } 
internal class Baz : IBaz 
{ 
    public Baz(IBar bar) 
    { 
    } 
}