Mini 容器学习笔记13——插件注入
Mini容器的插件注入是通过InjectMany的方式来注入多个组件的方式进行的,插件的元数据通过标签的方式进行配置,Mini容器在注入插件的过程中同时也可以把插件的元数据一起注入,这和MEF实现插件框架是一样的。 下面看看Mini容器怎样来实现插件架构的。
1. 定义插件接口契约,插件元数据标签以及插件元数据接口
//插件接口 [Contract] public interface IAddIn { void Start();//启动插件 }
//插件配置元数据标签 [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] [MetadataAttributeAttribute] public class AddInAttribute : ComponentAttribute { public string Name { get; set; } public string Author; public string Url; public string Version; } //插件元数据接口 public interface IAddInMetadata { string Name { get; } string Author { get; } string Url { get; } string Version { get; } }
2. 定义插件管理器
//插件管理器接口,用来启动和停止插件的 [Contract] public interface IAddInManager:IStartable { } [Component] public class AddInManager:IAddInManager { [InjectMany] IEnumerable<Lazy<IAddIn, IAddInMetadata>> AddIns { get; set; } public void Start() { foreach (var item in AddIns) { Console.WriteLine(string.Format("Name={0},Author={1},Url={2},Version={3}", item.Metadata.Name,item.Metadata.Author,item.Metadata.Url,item.Metadata.Version)); item.Value.Start(); } } public void Stop() { } }
3. 实现插件
public abstract class AddInBase : IAddIn { public virtual void Start() { } }
[AddIn(Name = "Dashboard", Author = "Kevin Wang", Url = "http://netcasewqs.cnblogs.com", Version = "1.0")] public class DashboardAddIn : AddInBase { public override void Start() { Console.WriteLine("Dashboard start..."); } } [AddIn(Name = "Editor", Author = "Kevin Wang", Url = "http://netcasewqs.cnblogs.com", Version = "1.0")] public class EditorAddIn : AddInBase { public override void Start() { Console.WriteLine("Editer start..."); } } [AddIn(Name = "PlayList", Author = "Kevin Wang", Url = "http://netcasewqs.cnblogs.com", Version = "1.0")] public class PlaylistAddIn : AddInBase { public override void Start() { Console.WriteLine("PlayList start..."); } }
4. 创建宿主程序并测试
[TestFixture] public class AddInTest:TestBase { [Inject] IAddInManager AddInManager; [Test] public void Test() { ServiceRegistry .Register<AddInManager>() .Register<DashboardAddIn>() .Register<EditorAddIn>() .Register<PlaylistAddIn>(); ServiceRegistry.Compose(this); } }
5. 查看运行结果:
Mini 容器官方网站:
推荐资源: