为什么我的Windsor Implicit Delegate Factory Registration不起作用?

时间:2012-04-17 18:49:52

标签: c# castle-windsor ioc-container

我试图让这个工作 - 但我必须遗漏一些东西 http://docs.castleproject.org/Windsor.Typed-Factory-Facility-delegate-based-factories.ashx#Registering_factories_implicitly_1

有人能发现它吗?

[TestClass]
public class UnitTest1 {

    [TestMethod]
    public void DelegateFactoryTest() {
        var container = new WindsorContainer();
        container.Register(
            Component.For<AComponent>().LifeStyle.Transient,
            Component.For<IAService>().ImplementedBy<AService>().LifeStyle.Transient
            );

        var comp = container.Resolve<AComponent>();
        Assert.IsNotNull(comp);
        Assert.IsNotNull(comp.GetService());
    }

    class AComponent {
        readonly Func<IAService> _serviceDelegate;

        public AComponent(Func<IAService> serviceDelegate) {
            _serviceDelegate = serviceDelegate;
        }

        public IAService GetService() {
            return _serviceDelegate();
        }
    }

    interface IAService { }

    class AService : IAService { }
}

收到以下错误

Castle.MicroKernel.Handlers.HandlerException:无法创建组件'Sandbox.Windsor.Tests.UnitTest1 + AComponent',因为它具有要满足的依赖项。 'Sandbox.Windsor.Tests.UnitTest1 + AComponent'正在等待以下依赖项: - 服务'System.Func`1 [[Sandbox.Windsor.Tests.UnitTest1 + IAService,Sandbox.Windsor.Tests,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]]'未注册。

如果我明确注册,一切都很好

container.Register(
    Component.For<AComponent>().LifeStyle.Transient,
    Component.For<IAService>().ImplementedBy<AService>().LifeStyle.Transient,
    Component.For<Func<IAService>>().Instance(()=>new AService()).LifeStyle.Transient
);

1 个答案:

答案 0 :(得分:5)

你错过了TypedFactoryFacility

container.AddFacility<TypedFactoryFacility>()