Make your ASP.NET application extendable
26. July 2007People have asked me how we build the extension model into BlogEngine.NET. There’s nothing to it - really, there isn’t.
You need one small class and 14 lines of code in the global.asax. That is all you need to make your ASP.NET application extendable. An extension is just a normal class that is somehow marked as being an extension. No magic is needed.
The scenario I liked best was one where you could just drop your custom extension into the App_Code folder and then it would just work. Reflection would take care of creating an instance of the extension, but we need a way to separate the extensions from all other classes in the App_Code folder. That’s where we need the small class.
The class
I decided it would make most sense to have all custom extensions be decorated with a custom attribute called Extension and then let global.asax activate them when the application starts. That would make the class definition of a custom extension look like this:
[Extension("description")]
public class MyCustomExtension
To do that, we need to write a very small class that inherits from System.Attribute and it looks like this:
public class ExtensionAttribute : System.Attribute
{
/// <summary>
/// Creates an instance of the attribute and assigns a description.
/// </summary>
public ExtensionAttribute(string description)
{
_Description = description;
}
private string _Description;
/// <summary>
/// Gets the description of the extension.
/// </summary>
public string Description
{
get { return _Description; }
}
}
It’s a very simple class that just has a description property and that’s it. The description property is not really needed to implement extensions, so you can leave it out if you’d like.
Global.asax
Now we have our custom attribute, so it’s time to let global.asax use reflection to activate the extensions. This method iterates through all the types in the App_Code folder and when it finds a class that is decorated with the Extension attribute then it creates an instance of it.
void Application_Start(object sender, EventArgs e)
{
Assembly a = Assembly.Load("__code");
Type[] types = a.GetTypes();
foreach (Type type in types)
{
object[] attributes = type.GetCustomAttributes(typeof(ExtensionAttribute), false);
foreach (object attribute in attributes)
{
a.CreateInstance(type.FullName);
}
}
}
That’s it. Now your ASP.NET application handles custom extensions made by who ever wants to write them. There are many ways to customize this implementation. For instance, you can put the reflection code in the Begin_Request method instead of the Application_Start to let your extensions act as an HttpModule.
本文介绍了一种简单的方法来使ASP.NET应用程序具备扩展性。通过定义一个自定义属性`Extension`并使用反射机制,可以在应用程序启动时自动激活放置于`App_Code`目录下的自定义扩展。这种方式不需要复杂的配置,只需几行代码即可实现。
3408

被折叠的 条评论
为什么被折叠?



