无实现类型的工厂问题

时间:2011-08-01 18:34:00

标签: dependency-injection castle-windsor

举个简单的例子:

class Program
{
    static void Main(string[] args)
    {
        var windsorContainer = new WindsorContainer();
        windsorContainer.Install(new WindsorInstaller());

        var editor = windsorContainer.Resolve<IEditor>();
        editor.DoSomething();

        Console.ReadKey();
    }
}

public class WindsorInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.AddFacility<TypedFactoryFacility>();

        container.Register(Component.For<ISomeOtherDependency>().ImplementedBy<SomeOtherDependency>());
        container.Register(Component.For<IReviewingService>().ImplementedBy<ReviewingService>());
        container.Register(Component.For<IEditor>().ImplementedBy<Editor>());
        container.Register(Component.For<Func<IReviewingServiceFactory>>().AsFactory());
    }
}

public interface IEditor
{
    void DoSomething();
}

public class Editor : IEditor
{
    private readonly Func<IReviewingServiceFactory> _reviewingService;

    public Editor(Func<IReviewingServiceFactory> reviewingService)
    {
        _reviewingService = reviewingService;
    }

    public void DoSomething()
    {
        var rs = _reviewingService();
        var reviews = new List<string> {"Review #1", "Review #2"};
        var reviewingService = rs.Create(reviews);

        reviewingService.Review();
    }
}

public interface IReviewingServiceFactory
{
    IReviewingService Create(IList<string> reviews);
}

public interface IReviewingService
{
    void Review();
}

public class ReviewingService : IReviewingService
{
    private readonly IList<string> _reviews;
    private readonly ISomeOtherDependency _someOtherDependency;

    public ReviewingService(IList<string> reviews, ISomeOtherDependency someOtherDependency)
    {
        _reviews = reviews;
        _someOtherDependency = someOtherDependency;
    }

    public void Review()
    {
        Console.WriteLine("Reviewing...");
    }
}

public interface ISomeOtherDependency
{
}

public class SomeOtherDependency : ISomeOtherDependency
{
}

通过这个例子,我希望控制台输出“Reviewing ...”。然而,温莎抛出异常:

No component for supporting the service CastleWindsorTypedFactor.IReviewingServiceFactory was found

我的Windsor安装程序有什么问题?

1 个答案:

答案 0 :(得分:5)

您已注册Func<IReviewingServiceFactory>而不是IReviewingServiceFactory ...请尝试替换

container.Register(Component.For<Func<IReviewingServiceFactory>>().AsFactory());

container.Register(Component.For<IReviewingServiceFactory>().AsFactory());

并相应地调整代码 - 然后它应该可以工作。

哦,还有一件事 - 您注册了IReviewingService而未指定生活方式,这将默认为SINGLETON。这很可能你想要什么,因为那时你的reviews参数只会在创建时传递给实例 ,这只会在第一次发生时工厂被称为......!对工厂的额外调用将​​返回单例实例。

因此:将IReviewingService的生活方式更改为瞬态,并在工厂界面上创建适当的发布方法签名(例如void Destroy(IReviewingService service))。