.net - 温莎城堡内部构造函数/类

标签 .net dependency-injection inversion-of-control castle-windsor

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

Castle Windsor: Register class with internal constructor?

但是您可以使用 Windsor 来使用内部构造函数/类以及依赖项注入(inject)吗? (所以构造函数参数也被注入(inject))?我希望将类/构造函数保留在内部,以实现最佳封装(这些类不应公开给公众)。

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

Castle Windsor: How to register internal implementations

谢谢。

最佳答案

这可能不是一个令人满意的答案,但最佳实践是使用公共(public)构造函数将您需要通过 CaSTLe 实例化的所有类设为公共(public)。您的设计应该允许下游依赖项实例化您的对象,而不依赖于 CaSTLe 或 InternalsVisibleTo。

对于你的问题,CaSTLe 只会搜索公共(public)构造函数来实例化对象。我不相信有办法让它搜索内部或私有(private)构造函数。但是,如果您的类是内部类,则可以将内部构造函数公开,而无需更改封装。请参阅以下测试用例:

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

关于.net - 温莎城堡内部构造函数/类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4017068/

相关文章:

c# - AnonymousPipeServerStream.Read() 偶尔会在客户端退出时挂起

c# - Foreach输出成两列cshtml

unit-testing - 从测试覆盖中排除代码

c# - 通过 MSMQ 进行通信的 Windows 服务 - 我需要服务总线吗?

.net - 您如何以编程方式(重新)签署具有强名称的 .NET 程序集?

rest - 如何使用 Jersey 将依赖项注入(inject)资源?

c# - Autofac ContainerBuilder.Build 是一项昂贵的操作吗?

asp.net-mvc - 您可以使用 IOC 容器将依赖项注入(inject)自定义 WebViewPage 的构造函数吗?

c# - 使用什么是组合 Autofac 和 Dapper 的首选方式

.net - 使用装饰器模式的 Ninject 依赖注入(inject)