这可能不是一个令人满意的答案,但最好的做法是让所有需要使用公共构造函数通过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