8

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

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

public class MyViewModel
{
   private IAnotherViewModelFactory factory;

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

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

4

3 回答 3

7

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

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


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

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

于 2010-11-06T16:14:52.597 回答
3

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

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

如果这个类在容器中注册,AnotherViewModelAutofac 将Func<AnotherViewModel>隐式提供实现:

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

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

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

于 2010-11-12T23:31:11.337 回答
1

我最近为 Unity 实现了相当于 Castle Windsor Typed Factories 的功能。您可以在https://github.com/PombeirP/Unity.TypedFactories找到该项目,在 http://nuget.org/packages/Unity.TypedFactories找到 NuGet 包。

用法如下:

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

参数匹配是按名称完成的,这很适合我的需求,尽管可以轻松扩展该库以支持其他需求。

于 2012-12-06T21:35:10.537 回答