浅谈BlogEngine扩展机制的实现

in Develop

以前写过一个针对于Blogengine的Mp3播放器扩展
在Blogengine里,每一个扩展的Class都必须有Extension标记
ExtensionAttribute是一个密封类,继承自System.Attribute,System.Attribute没有任何实现,只是一个标记而已。
ExtensionAttribute类的代码:

[AttributeUsage(AttributeTargets.Class)] //指明该Attrubite只能应用于Class上
public sealed class ExtensionAttribute : System.Attribute
{
/// <summary>
/// Creates an instance of the attribute and assigns a description.
/// </summary>
public ExtensionAttribute(string description, string version, string author)
{
_Description = description;
_Version = version;
_Author = author;
}

private string _Description;
/// <summary>
/// Gets the description of the extension.
/// </summary>
public string Description
{
get { return _Description; }
}

private string _Version;

/// <summary>
/// Gets the version number of the extension
/// </summary>
public string Version
{
get { return _Version; }
}

private string _Author;

/// <summary>
/// Gets the author of the extension
/// </summary>
public string Author
{
get { return _Author; }
}

}

这个类非常之简单,只是一些描述性的信息,如作者、版本、描述等。
到这里,ExtensionAttribute类就可以应用在任何一个Class上了
看看mp3player.cs

/// <summary>
/// 增加flashMp3播放器
/// </summary>
[Extension("mp3 player", "1.0.0.0", "lemongtree.com")] //此处给mp3player类打上Extension标记
public class mp3player
{
public mp3player()
{
Post.Serving += new EventHandler<ServingEventArgs>(Post_Serving);
}
private void Post_Serving(object sender, ServingEventArgs e)
{
//此处略过
}
}

mp3player就是一个针对于Post的扩展了。
有朋友可能会问了:mp3player这个在什么时候实例化的呢?或是我如何得知这个扩展是不是Enable的呢?
整个实例化的过程在global.asax的Application_Start事件中

Assembly a = Assembly.Load(assemblyName);
Type[] types = a.GetTypes(); //获取当前程序集中的所有类型

foreach (Type type in types)
{
object[] attributes = type.GetCustomAttributes(typeof(ExtensionAttribute), false); //获取含有ExtensionAttribute标记的类
foreach (object attribute in attributes)
{
if (ExtensionManager.ExtensionEnabled(type.Name))
{
a.CreateInstance(type.FullName); //创建实例
}
}
}

到这里很明了了,扩展类决定于它有没有打Extension标记,是否创建实例取决于该扩展有没有被启用.
BlogEngine有很多地方是值得我们学习的.

4 Comments

4 Comments

  1. 呵呵,最近也在研究BlogEngine Core部分,参考下你的文章,还怪容易理解的。^_^

  2. 看得不是很懂。:(

  3. 我也研究了BlogEngine

Leave a Reply

Using Gravatars in the comments - get your own and be recognized!

XHTML: These are some of the tags you can use: <a href=""> <b> <blockquote> <code> <em> <i> <strike> <strong>