是否有任何其他.NET IoC容器提供与Castle Windsor中的类型化工厂设施等效的功能?
例如,如果我在WPF应用程序中使用抽象工厂模式:
public class MyViewModel
{
private IAnotherViewModelFactory factory;
public void ShowAnotherViewModel()
{
viewController.ShowView(factory.GetAnotherViewModel());
}
}我不想为我想要展示的每一种类型的ViewModel创建一个手动的IAnotherViewModelFactory实现,我希望容器能为我解决这个问题。
发布于 2010-11-07 00:14:53
AutoFac有一个名为Delegate Factories的特性,但据我所知,它只适用于委托,而不适用于接口。
我在StructureMap和Unity中都没有遇到任何类似于Castle的类型化工厂工具的东西,但这并不一定意味着它们不在那里……
我能想象到的唯一方法就是通过动态代理为接口实现类似的东西。由于Castle Windsor有一个动态代理,但很少有其他容器有类似的代理,这可能有助于解释为什么这个特性并不普遍。
Unity还提供拦截功能,因此它必须具有某种动态代理实现,但我非常确定它没有任何等同于类型化工厂的东西。与其他容器相比,Unity是相当基础的。
发布于 2010-11-13 07:31:11
在Autofac中,你可以在Mark提到的委托方法之上实现类型化工厂。例如。
class AnotherViewModelFactory : IAnotherViewModelFactory {
Func<AnotherViewModel> _factory;
public AnotherViewModelFactory(Func<AnotherViewModel> factory) {
_factory = factory;
}
public AnotherViewModel GetAnotherViewModel() {
return _factory();
}
}如果这个类是在容器中注册的,AnotherViewModel Autofac将隐式地提供Func<AnotherViewModel>实现:
builder.RegisterType<AnotherViewModel>();
builder.RegisterType<AnotherViewModelFactory>()
.As<IAnotherViewModelFactory>();实际上,您可以使用类型化工厂工具实现的任何接口都可以使用这种方法在Autofac中实现。主要区别在于,Windsor实现通过组件注册API配置工厂,而在Autofac中,工厂本身就是一个组件。
对于更复杂的示例,您可能想看看:http://code.google.com/p/autofac/wiki/RelationshipTypes和http://nblumhardt.com/2010/01/the-relationship-zoo/。
发布于 2012-12-07 05:35:11
我最近为Unity实现了一个等同于Castle Windsor类型工厂的东西。您可以在https://github.com/PombeirP/Unity.TypedFactories上找到该项目,在http://nuget.org/packages/Unity.TypedFactories上找到NuGet包。
用法如下:
unityContainer
.RegisterTypedFactory<IFooFactory>()
.ForConcreteType<Foo>();参数匹配是按名称完成的,这符合我的需求,尽管该库可以很容易地扩展以支持其他需求。
https://stackoverflow.com/questions/4113382
复制相似问题