Caliburn笔记-依赖注入容器(wpf框架)

前端之家收集整理的这篇文章主要介绍了Caliburn笔记-依赖注入容器(wpf框架)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

参考与此http://caliburn.codeplex.com/wikipage?title=Auto-Registering%20Components&referringTitle=Documentation

此为基础,看了没用,不看不行…了解下注册流程.


注册组件,差不多离不开这几种模式

  1. 手动注册
  2. 元数据标签注册
  3. 外部dll加载注册

1.内置服务则用手动注册.

2.挂元数据标签,如下

  1. [PerRequest(typeof(IHomePresenter))]
  2. public class HomePresenter : Presenter,IHomePresenter
  3. {
  4. }


以前不是推荐此种做法的,标签会产生框架耦合,但框架用都用了,内置demo使用此方法最多,之前用的是手动注册,框架会去dll中寻找挂此标签的对象然后自动注册.

3.外部dll加载

重写CaliburnApplication的SelectAssemblies方法

  1. protected override System.Reflection.Assembly[] SelectAssemblies()
  2. {
  3. return new[] { Assembly.GetEntryAssembly(),typeof(Caliburn.WPF.ApplicationFramework.Bind).Assembly};
  4. }
@L_301_1@
  1. private void InspectAssembly(Assembly assembly,ICollection<ComponentInfo> componentList,ICollection<Type> configs)
  2. {
  3. var types = assembly.GetExportedTypes();
  4.  
  5. foreach (var type in types)
  6. {
  7. foreach (var attribute in type.GetCustomAttributes(true).OfType<RegisterAttribute>())
  8. componentList.Add(attribute.GetComponentInfo(type));
  9. }
  10.  
  11. foreach (var type in types)
  12. {
  13. if(_configType.IsAssignableFrom(type) && !type.IsAbstract)
  14. configs.Add(type);
  15. }
  16. }


总的来说,我们只要加载dll,挂上标签就可以自动注册

内置服务+自定义服务注册好以后,接下来的任务就是注册实例.即组件的生命周期状况.内置都为Singleton

  1. /// <summary>
  2. /// The lifetime of a Caliburn component.
  3. /// </summary>
  4. public enum ComponentLifetime
  5. {
  6. /// <summary>
  7. /// One instance per application.
  8. /// </summary>
  9. Singleton,/// <summary>
  10. /// A new instance is created on each request.
  11. /// </summary>
  12. PerRequest,/// <summary>
  13. /// A new instance is created per custom lifetime rules.
  14. /// </summary>
  15. Custom
  16. }


可以通过重写ConfigureWith方法,使用第三方容器来注册服务,当然其内置也提供了一个较为简单的容器

新版本可能会更新,所以不去研究它了

猜你在找的设计模式相关文章