Jef*_*eff 7 .net dependency-injection castle-windsor inversion-of-control
我看了这个,它回答了我的一半问题:
但是你可以使用Windsor来使用内部构造函数/类以及依赖注入吗?(所以构造函数参数也被注入)?我想保持类/构造函数内部允许最佳封装(这些类不应暴露给公众).
我需要这个来支持Silverlight,所以我不认为这是一个选项:
谢谢.
这可能不是一个令人满意的答案,但最佳做法是使用公共构造函数通过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)
{
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1858 次 |
| 最近记录: |