在 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>();
实际上,您可以使用 Typed Factory Facility 实现的任何接口都可以使用这种方法在 Autofac 中实现。主要区别在于 Windsor 实现通过组件注册 API 配置工厂,而在 Autofac 中,工厂本身就是一个组件。
对于更复杂的示例,您可能希望查看:http ://code.google.com/p/autofac/wiki/RelationshipTypes和http://nblumhardt.com/2010/01/the-relationship-zoo/。