过滤式设施工厂注册

时间:2014-07-02 23:07:29

标签: c# castle-windsor

我目前正在按照自己的声明注册每个Typed Facility Factory

_container.Register(Component.For<IDataSourcePickerViewModelFactory>().AsFactory());
_container.Register(Component.For<IDataSourcePickerFactory>().AsFactory());
_container.Register(Component.For<ISetSaveAsFactory>().AsFactory());
_container.Register(Component.For<ISetSaveAsViewModelFactory>().AsFactory());

有没有办法根据命名空间执行此操作?一些东西(伪代码)

_container.Register(Classes.FromThisAssembly()
    .InNamespace("MyProject.View")
    .Where(x => x.InterfaceName.EndsWith("Factory"))
    .AsFactory());

1 个答案:

答案 0 :(得分:1)

using (var container = new WindsorContainer())
{
    container.AddFacility<TypedFactoryFacility>();

    container.Register(
        Component.For<IBoo>().ImplementedBy<Boo>().LifestyleTransient(),
        Component.For<IBar>().ImplementedBy<Bar>().LifestyleTransient(),

        Types.FromThisAssembly()
            .Where(c => c.Namespace == "MyFactories" && c.Name.EndsWith("Factory"))
            .Configure(c=>c.AsFactory())
        );

    var booFactory = container.Resolve<IBooFactory>();
    var boo = booFactory.Create();
    Console.WriteLine(boo.GetType().FullName);
    booFactory.FreeUp(boo);

    var barFactory = container.Resolve<IBarFactory>();
    var bar = barFactory.Create();
    Console.WriteLine(bar.GetType().FullName);
    barFactory.FreeUp(bar);
}   


namespace MyFactories
{
    public interface IBooFactory
    {
        IBoo Create();
        void FreeUp(IBoo cmp);
    }

    public interface IBarFactory
    {
        IBar Create();
        void FreeUp(IBar cmp);
    }

    public interface IBar{}

    public interface IBoo{}

    public class Boo : IBoo{}

    public class Bar : IBar{}

}