1

通过使用微软的统一,我能够覆盖的确切时刻的依赖是我解决一个实例,例如:IoC:创建一个Unity扩展来覆盖依赖关系?

var valueObjectThatOverridesAnyConfiguration = new object(); 

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

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

有没有一种方法来指定它在容器级别?像扩展或什么的?我不想在决定的时刻做到这一点!

谢谢!让我知道如果我迷惑你,我会提供更多信息。

+2

我不明白你的目标是什么。如果你想用相同的构造函数参数指定一个容器范围的依赖覆盖,为什么不用你的'ATypeWithConstructorArguments'类型注册该参数?所以你不需要重写。 – nemesv 2011-12-19 19:44:16

+0

原因我不想在每次构造函数依赖项更改时更改寄存器。 我真正想要的是说:“当你找到这个需求时,不论其他依赖关系如何,提供这个实例。所以如果我注册了类型,每次我的构造函数改变时我都必须更改注册表。 – Pato 2011-12-19 19:57:59

+0

这听起来像你真正需要的是支持自动注册/约定而不是配置。 Unity并没有提供开箱即用的功能,而Castle Windsor,Autofac和StructureMap则提供了... – 2011-12-20 07:27:39

回答

3

你的意思是类似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)); 

来源可以发现hereTecX.Unity项目中。

+0

非常感谢! – Pato 2011-12-20 13:56:16