为了在整个应用程序中使用相同的 Castle 容器,请创建一个静态类,例如:
public static class CastleContainer {
private static IWindsorContainer container;
public static IWindsorContainer Instance {
get {
if (container == null) {
container = new WindsorContainer();
}
return container;
}
// exposing a setter alleviates some common component testing problems
set { container = value; }
}
// shortcut to make your life easier :)
public static T Resolve<T>() {
return Instance.Resolve<T>();
}
public static void Dispose() {
if (container != null)
container.Dispose();
container = null;
}
}
然后在Main() 方法中注册/安装所有组件。您还可以挂钩到应用程序关闭事件以调用 Dispose()(尽管这并不重要)。
Castle 实际上在其quick-start guide 中使用了一个 Windows 窗体应用程序。
编辑:
我上面展示的模式是服务定位器的一种变体,有些人称之为反模式。它的名声不好,因为除其他原因外,它通过引用 Windsor 来增加您的代码库。理想情况下,您应该只调用一次container.Resolve<...>() 来创建您的根表单。所有其他服务和表单都是通过构造函数注入的。
实际上,您可能需要多次调用 Resolve,特别是如果您不想在启动时加载应用程序的每个角落。在 Web 世界中,最佳实践是将容器交给 Web 框架。在 Windows 窗体世界中,您需要实现自己的服务定位器,如上所示。 (是的,将容器交给 ASP.NET MVC 框架仍然是一种服务定位器模式)。
我已经编辑了上面的代码示例,以便静态容器是可注入的;没有资源被绑定在静态上下文中。如果您最终创建了自己的服务定位器,您可能还想创建一个像这样的测试实用程序来简化测试。
public static class TestUtilities
{
public static IContainer CreateContainer(Action<IContainer> extraConfig = null)
{
var container = new WindsorContainer();
// 1. Setup common mocks to override prod configuration
// 2. Setup specific mocks, when provided
if (extraConfig != null)
extraConfig(container);
// 3. Configure container with production installers
CastleContainer.Instance = container;
return container;
}
}
这为创建一个看起来很像生产版本的新容器提供了一种快捷方式,但其中一些服务被替换为模拟。一些示例测试可能如下所示:
[Test]
public void SubComponentWorksGreat()
{
using (var container = TestUtilities.CreateContainer())
{
var subComponent = container.Resolve<SubComponent>();
// test it...
}
}
[Test]
public void SubComponentWorksGreatWithMocks()
{
var repoMock = new Mock<IRepository>();
using (var container = TestUtilities.CreateContainer(c =>
c.Register(Component.For<IRepository>().Instance(repoMock.Object))))
{
var subComponent = container.Resolve<SubComponent>();
// test it with all IRepository instances mocked...
}
}
最后一点。为每个测试创建一个完整的容器可能会很昂贵。另一种选择是创建完整容器,但仅使用嵌套容器进行实际测试。