Unity 笔记一
配置Unity有两种方法:利用配置文件配置;在程序代码中配置。
以The Unity StopLight QuickStart为例:
在程序中用代码配置,这种方法重新配置需重新编译程序。
IUnityContainer container = new UnityContainer() .AddNewExtension<SimpleEventBrokerExtension>(); .RegisterType<ILogger, TraceLogger>() .RegisterType<IStoplightTimer, RealTimeTimer>();
另一种方式是利用配置文件配置:配置文件配置是应添加
xmlns ="http://schemas.microsoft.com/practices/2010/unity",这样可以利用xsd架构来智能感知。
<configSections> <section name ="unity" type ="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/> </configSections> <unity xmlns ="http://schemas.microsoft.com/practices/2010/unity"> <namespace name="StopLight.ServiceInterfaces"/> <namespace name="StopLight.ServiceImplementations"/> <namespace name="StopLight.UI"/> <namespace name="StopLight.Logic"/> <assembly name="StopLight"/> <container> <register type="ILogger" mapTo="TraceLogger"/> <register type="IStoplightTimer" mapTo="RealTimeTimer"/> <register type="Stoplight"> <property name="Logger" dependencyType="ILogger" dependencyName="TraceLogger"/> </register> <register type="StoplightSchedule"> <property name="Logger" dependencyType="ILogger" dependencyName="TraceLogger"/> </register> <register type="StoplightPresenter"> <property name="Stoplight" dependencyType="Stoplight" dependencyName="Stoplight"/> <property name="Schedule" dependencyType="StoplightSchedule" dependencyName="StoplightSchedule"/> </register> </container> </unity>
IUnityContainer container = new UnityContainer(); UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); section.Configure(container);