将参数传递给构造函数。在第1单元中,当您通过 new InjectionConstruction (...)注册类型时,您只能设置一个值
有 ParameterOverride : ResolverOverride
一个 ResolverOverride 类,它允许您
重写传递给
构造函数。
与 DependencyOverride : ResolverOverride的依赖关系也是如此
重写值的类
每当有一个
给定类型的依赖项,
无论它出现在
目标图目标图。
对于具有 PropertyOverride : ResolverOverride的属性也是如此
允许您重写指定属性的值的 ResolverOverride。
例子
using System;
using Microsoft.Practices.Unity;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
var container = new UnityContainer();
//ParameterOverride example
container.RegisterType<IConcreteService, ConcreteService>(
new InjectionConstructor(7) //Old way to pass value to constructor - not flexible.
//All resolved (without override which appears only in unity 2.0) classes will have val=7
);
var service0 = container.Resolve<IConcreteService>();
Console.WriteLine(service0.Val); //prints 7
var service = container.Resolve<IConcreteService>(new ParameterOverride("val", 3));
Console.WriteLine(service.Val); // prints 3
var service2 = container.Resolve<IConcreteService>(new ParameterOverride("val", 5));
Console.WriteLine(service2.Val); // prints 5
Console.ReadLine();
//DependencyOverride example
var b0 = container.Resolve<B>(new DependencyOverride<IConcreteService>(new ConcreteService(42)));
Console.WriteLine(b0.Service.Val); //print 42
Console.WriteLine(b0.Service1.Val); //print 42
var b = container.Resolve<B>(new DependencyOverride<IConcreteService>(new ConcreteService(-42)));
Console.WriteLine(b.Service.Val); // print -42
Console.WriteLine(b.Service1.Val); // print -42
Console.ReadLine();
//PropertyOverride example
var b1 = container.Resolve<B>(new PropertyOverride("Service", new ConcreteService(42)),
new PropertyOverride("Service1", new ConcreteService(-42)));
Console.WriteLine(b1.Service.Val); //print 42
Console.WriteLine(b1.Service1.Val); //print -42
Console.ReadLine();
}
}
public interface IConcreteService {
int Val { get; set; }
}
public class ConcreteService : IConcreteService {
public int Val { get; set; }
public ConcreteService(int val) {
Val = val;
}
}
public class B {
[Dependency]
public IConcreteService Service{ get; set; }
[Dependency]
public IConcreteService Service1 { get; set; }
}
}