代码之家  ›  专栏  ›  技术社区  ›  Jeff

城堡温莎内部建造商/等级

  •  6
  • Jeff  · 技术社区  · 14 年前

    我看了一下,它回答了我一半的问题:

    Castle Windsor: Register class with internal constructor?

    但是,可以使用windsor在依赖注入的同时使用内部构造函数/类吗?(所以也注入了构造函数参数)?我希望将类/构造函数保持在内部,以便实现最佳封装(这些类不应公开)。

    我需要这个来支持Silverlight,所以我不认为这是一个选项:

    Castle Windsor: How to register internal implementations

    谢谢。

    1 回复  |  直到 14 年前
        1
  •  7
  •   Stuart Lange    14 年前

    [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)
        {
        }
    }