我在 C# 中做了一个项目,该项目生成一个 .dll 文件,其中包含从 SQL 数据库上的查找表生成的动态枚举。这工作正常,运行项目,生成 dll。
现在我需要将此 dll 包含在另一个项目中才能使用这些枚举,但我必须确保每次运行我的项目时,枚举 dll 都是最新的。
在运行包含枚举 dll 的主项目之前,如何运行我的枚举 dll 项目?有什么解决办法吗?
using System;
using System.Data.SqlClient;
using System.Reflection;
using System.Reflection.Emit;
namespace DynamicEnums
{
class EnumCreator
{
static void Main(string[] args)
{
const string connectionString =
"Integrated Security=SSPI;Persist " +
"Security Info=False;Initial Catalog=MyDB;Data Source=MyServer;" +
"MultipleActiveResultSets=True";
// Define Namespace name
const string nameSpace = "EnumTypes";
// Define Assembly name
const string strAssemblyName = "MyEnums";
// Table Suffix
const string tableSuffix = "TypeEnum";
var mainQuery = string.Format("Select SCHEMA_NAME(schema_id) as [Schema], Name" +
" from sys.tables where name like '%{0}'", tableSuffix);
// Get the current application domain for the current thread
var currentDomain = AppDomain.CurrentDomain;
// Create a dynamic assembly in the current application domain,
// and allow it to be executed and saved to disk.
var name = new AssemblyName(strAssemblyName);
var assemblyBuilder =
currentDomain.DefineDynamicAssembly(name,
AssemblyBuilderAccess.RunAndSave);
var moduleBuilder =
assemblyBuilder.DefineDynamicModule(name.Name, name.Name + ".dll");
#region GetTheDataFromTheDatabase
//Search for all Enum Lookup Tables
using (var dbConn = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand())
{
dbConn.Open();
cmd.Connection = dbConn;
cmd.CommandText = mainQuery;
SqlDataReader readerTables = cmd.ExecuteReader();
while (readerTables.Read())
{
using (var cmdEnum = new SqlCommand())
{
cmdEnum.Connection = dbConn;
cmdEnum.CommandText = string.Format("Select [{0}Id], [Name] from {1}.{0}",
readerTables["Name"],
readerTables["Schema"]);
SqlDataReader readerEnums = cmdEnum.ExecuteReader();
// Define a public enumeration and an underlying type of Integer
var myEnum = moduleBuilder.DefineEnum(
string.Format("{0}.{1}", nameSpace, readerTables["Name"]),
TypeAttributes.Public,
typeof(int)
);
while (readerEnums.Read())
{
myEnum.DefineLiteral(readerEnums[1].ToString(),
Convert.ToInt32(readerEnums[0].ToString()));
}
// Create the enum
myEnum.CreateType();
readerEnums.Close();
}
}
readerTables.Close();
}
} //eof using
#endregion GetTheDataFromTheDatabase
// save assembly
assemblyBuilder.Save(name.Name + ".dll");
}
}
}