是否可以在不修改代码的情况下扩展 SubSonic 生成器?我想添加我自己的自定义方法,我可以在模板中使用。类似于 Utility.GetVariableType 方法的东西。
4 回答
您不能扩展内置模板,但您可以用您自己的模板替换它们,而无需更改 SubSonic.dll。在此处查看 templateDirectory 参数:http: //subsonicproject.com/docs/Generated_Classes/#Customizing_Active_Record
一个示例配置是:
<SubSonicService defaultProvider="Northwind" enableTrace="true"
templateDirectory="C:\Program Files\SubSonic\SubSonic 2.0.3\Templates\MVC">
<providers>
<clear/>
<add name="Northwind" type="SubSonic.SqlDataProvider, SubSonic"
connectionStringName="Northwind" generatedNamespace="Northwind"/>
</providers>
</SubSonicService>
您可以从此处获取当前版本的内置 ActiveRecord 模板。
我找到了解决我自己问题的方法:)。
我现在可以在模板中使用我需要的功能扩展 SubSonic,而无需重建或更改任何 SubSonic 代码本身。
它适用于我想做的事情,我认为它对其他人也有用,所以这里是:
创建一个新的类库 SubSonicHelper。我的课程看起来像这样:
using System; using System.Collections.Generic; using System.Text; namespace Helpers.SubSonic { public class GeneratorHelper { public bool IsColumnAllowed(string columnName) { return columnName.Length == 1 || (columnName.Length > 1 && (!(columnName[0].ToString().Equals("_") && columnName[columnName.Length - 1].ToString().Equals("_")))) } } }
- 构建程序集并将 SubSonicHelper.dll 复制到您的 subsonic 项目。
- 使用 templateDirectory 参数设置您的 SubSonic 项目以使用您自己的模板。
编辑您自己的模板,然后在以下
const bool showGenerationInfo = false;
System.Reflection.Assembly a = System.Reflection.Assembly.LoadFile( System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "SubSonicHelper.dll")); object instance = a.CreateInstance("Helpers.SubSonic.GeneratorHelper"); Type type = instance.GetType();
在此之后,您将拥有一个可以在模板中使用的 GeneratorHelper 实例。要访问这些方法,您需要执行以下操作:
- 为要使用的方法的参数创建一个对象数组。我将 columnName 参数设置为 col.propertyName。这是在 Update 方法中的 foreach (TableSchema.TableColumn col in cols) 循环内。
- 使用对象数组作为参数调用要使用的方法。
检查结果对象以查看方法的结果。
object[] arg = new object[]{col.PropertyName}; object isColumnAllowedResult = type.InvokeMember("IsColumnAllowed", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null, instance, arg); if (Convert.ToBoolean(isColumnAllowedResult))
就是这样!现在我可以用我想在模板中使用的其他方法来扩展 SubSonicHelper 类。
最简洁的答案是不。如果您想出一些有用的东西,请提交一个补丁,它可能会集成到核心中。您可以在此处提交补丁:http ://code.google.com/p/subsonicproject/issues/list
你不能在模板中导入dll吗?
比如
<%@ Import namespace="NewHelpers.Utilities"%>
然后调用函数或者创建对象的实例