這可能不是一個令人滿意的答案,但最好的做法是讓所有需要使用公共構造函數通過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)
{
}
}
恕我直言,這不是最佳封裝。如果你需要Windsor來訪問這些類,那麼它們沒有被恰當地封裝。寫一個門面或讓它們公開。 – 2010-10-26 13:33:56
我不確定我是否理解。我有一個服務公共接口IMyService。我不希望該服務的消費者看到該實現。所以我有實現內部類MyService:IMyService。這種情況如何不代表最佳封裝? – Jeff 2010-10-26 14:44:29
你讓內部類型與接口混淆。這些是正交的問題。 – 2010-10-26 19:40:39