Unity允许在构造一个类型实例时对constructor、property、method进行依赖注入。比如ILogger的实现类型MyLogger有一个属性LogWritter,类型是TextWriter。它依赖一个名为LogWriter的类型注册,ILogger和MyLogger的定义如下:
1 public interface ILogger 2 { 3 TextWriter LogWriter { get; } 4 } 5 6 public sealed class MyLogger : ILogger 7 { 8 public TextWriter LogWriter { get; set; } 9 }
首先注册一个名为LogWriter的类型:
<unity xmlns=”http://schemas.microsoft.com/practices/2010/unity”> <assembly name=”mscorlib, 2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″ /> <container> <register name=”LogWriter” type=”System.IO.TextWriter” mapTo=”System.IO.StringWriter”> <constructor /> </register> </container> </unity>
再注册ILogger和它的实现:
<register type=”UnityTest3.ILogger, UnityTest3″ mapTo=”UnityTest3.MyLogger, UnityTest3″ />
现在为MyLogger添加property LogWriter的依赖,设置dependencyName为LogWriter、dependencyType为System.IO.TextWriter:
<register type=”UnityTest3.ILogger, UnityTest3″ mapTo=”UnityTest3.MyLogger, UnityTest3″> <property name=”LogWriter” dependencyName=”LogWriter” dependencyType=”System.IO.TextWriter” /> </register>
编写代码获取ILogger:
1 IUnityContainer unityContainer = new UnityContainer(); 2 unityContainer.LoadConfiguration(); 3 4 ILogger logger = unityContainer.Resolve<ILogger>();