Unity的Deferring the Resolution of Objects
Unity给出一种延迟创建对象的方案,可以先获取对象的创建器 -> 再注册类型 -> 其余代码 -> 创建类型实例,创建器的类型必须是Func<T>,而不是和Func相同返回值的delegate。看一个简单示例:
1 UnityContainer unityContainer = new UnityContainer(); 2 unityContainer.LoadConfiguration(); 3 4 Func<TextWriter> createFactory = unityContainer.Resolve<Func<TextWriter>>(); 5 6 unityContainer.RegisterType<TextWriter, StringWriter>(new InjectionConstructor()); 7 8 TextWriter textWriter = createFactory();
由于4.0默认新增了Lazy<T>(3.5可以添加并行库System.Threading.dll的引用),可以将类型的创建延迟,稍做修改后的代码:
1 IUnityContainer unityContainer = new UnityContainer(); 2 unityContainer.LoadConfiguration(); 3 4 Func<TextWriter> createFactory = unityContainer.Resolve<Func<TextWriter>>(); 5 6 unityContainer.RegisterType<TextWriter, StringWriter>(new InjectionConstructor()); 7 8 Lazy<TextWriter> textWriter = new Lazy<TextWriter>(createFactory);