【问题标题】:Castle Windsor Typed Factory Facility equivalents温莎城堡型工厂设施等价物
【发布时间】:2010-11-06 14:00:16
【问题描述】:

任何其他 .NET IoC 容器是否提供与 Castle Windsor 中的类型化工厂设施等效的功能?

例如如果我在 WPF 应用程序中使用抽象工厂模式:

public class MyViewModel
{
   private IAnotherViewModelFactory factory;

   public void ShowAnotherViewModel()
   {
      viewController.ShowView(factory.GetAnotherViewModel());
   }
}

我不想为我希望展示的每种类型的 ViewModel 创建一个 IAnotherViewModelFactory 的手动实现,我希望容器为我处理这个问题。

【问题讨论】:

标签: castle-windsor unity-container ninject autofac abstract-factory


【解决方案1】:

AutoFac 有一个名为 Delegate Factories 的功能,但据我所知,它仅适用于委托,不适用于接口。

我在 StructureMap 和 Unity 中都没有遇到过类似于 Castle 的 Typed Factory Facility 的东西,但这并不一定意味着它们不存在......


我可以想象为接口实现这样的事情的唯一方法是通过动态代理。由于 Castle Windsor 有一个动态代理,但很少有其他容器有类似的东西,这可能有助于解释为什么这个功能并不普遍。

Unity 还提供拦截功能,因此它必须具有某种动态代理实现,但我很确定它没有任何与 Typed Factories 等效的功能。与其他容器相比,Unity 比较基础。

【讨论】:

  • 谢谢 Mark,这是否意味着如果您不使用 Castle 的 Typed Factory Facility,您通常会在每个工厂类中引用容器?
  • 不,这意味着我只是手动编码它们。如果太多,那么您可以使用泛型或其他形式的代码重用。
【解决方案2】:

在 Autofac 中,您可以在 Mark 提到的委托方法之上实现类型化工厂。例如

class AnotherViewModelFactory : IAnotherViewModelFactory {
    Func<AnotherViewModel> _factory;
    public AnotherViewModelFactory(Func<AnotherViewModel> factory) {
        _factory = factory;
    }
    public AnotherViewModel GetAnotherViewModel() {
        return _factory();
    }
}

如果这个类注册到容器中,连同AnotherViewModel Autofac 将隐式提供Func&lt;AnotherViewModel&gt; 实现:

builder.RegisterType<AnotherViewModel>();
builder.RegisterType<AnotherViewModelFactory>()
    .As<IAnotherViewModelFactory>();

实际上,您可以使用 Typed Factory Facility 实现的任何接口都可以使用这种方法在 Autofac 中实现。主要区别在于 Windsor 实现通过组件注册 API 配置工厂,而在 Autofac 中,工厂本身就是一个组件。

您可能希望查看更复杂的示例:http://code.google.com/p/autofac/wiki/RelationshipTypeshttp://nblumhardt.com/2010/01/the-relationship-zoo/

【讨论】:

  • +1,但GetAnotherViewModel的实现不应该是return _factory();吗?
  • 顺便说一句,这种技术在 Unity 中的工作方式完全相同。
【解决方案3】:

我最近为 Unity 实现了一个等效的 Castle Windsor Typed Factories。您可以在 https://github.com/PombeirP/Unity.TypedFactories 找到项目,在 http://nuget.org/packages/Unity.TypedFactories 找到 NuGet 包。

用法如下:

unityContainer
    .RegisterTypedFactory<IFooFactory>()
    .ForConcreteType<Foo>();

参数匹配是按名称完成的,这对我的需求来说很好,尽管该库可以很容易地扩展以支持其他需求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多