【问题标题】:IoC: Create a Unity extension to override dependencies?IoC:创建一个 Unity 扩展来覆盖依赖项?
【发布时间】:2011-12-19 19:24:11
【问题描述】:

通过使用 Microsoft 的 Unity,我可以在解析实例的确切时刻覆盖依赖项,例如:

var valueObjectThatOverridesAnyConfiguration = new object();

var container = new UnityContainer();
container.Resolve<ATypeWithConstructorArguments>(new DependencyOverride(typeof(object), valueObjectThatOverridesAnyPreviousConfiguration);

这将覆盖我的 UnityContainer 上的任何先前配置并注入我在 DependencyOverride 上提供的实例。

有没有办法在容器级别指定它?像扩展或什么?我不想在下定决心的时候这样做!

谢谢!如果我对您感到困惑,请告诉我,我会提供更多信息。

【问题讨论】:

  • 我不明白你的目标是什么。如果您想使用相同的构造函数参数指定容器范围的依赖覆盖,为什么不使用该参数注册您的ATypeWithConstructorArguments 类型?所以你不需要覆盖。
  • 因为我不想在每次构造函数依赖项更改时更改寄存器。我真正想要的是说“当你找到这个要求时,提供这个实例,不管其他依赖项”。因此,如果我注册类型,则每次构造函数更改时都必须更改寄存器。
  • 听起来您真正需要的是支持自动注册/约定优于配置。 Unity 不提供开箱即用的功能,而 Castle Windsor、Autofac 和 StructureMap 提供...
  • Unity 没有约定,但 Unity vNext 的 wishlist 上有一个增强的配置引擎

标签: c#-4.0 inversion-of-control unity-container ioc-container


【解决方案1】:

你的意思是像this。听起来像您的问题的部分从线程的中间开始。

它允许你这样做

  var container = new UnityContainer();
  container.AddNewExtension<SemanticGroupExtension>();

  container.RegisterGroup<IVehicle, Car>("Car").Use<IWheel, CarWheel>().Use<IEngine, CarEngine>();
  container.RegisterGroup<IVehicle, Motorcycle>("Motorcycle").Use<IWheel, MotorcycleWheel>().Use<IEngine, MotorcycleEngine>();

  var car = container.Resolve<IVehicle>("Car");
  Assert.IsInstanceOfType(car.Wheel, typeof(CarWheel));
  Assert.IsInstanceOfType(car.Engine, typeof(CarEngine));

  var motorcycle = container.Resolve<IVehicle>("Motorcycle");
  Assert.IsInstanceOfType(motorcycle.Wheel, typeof(MotorcycleWheel));
  Assert.IsInstanceOfType(motorcycle.Engine, typeof(MotorcycleEngine));

可以在 TecX.Unity 项目中找到 here 的源代码。

【讨论】:

    猜你喜欢
    • 2019-06-29
    • 2014-03-18
    • 1970-01-01
    • 2012-08-15
    • 2020-04-12
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多