调用时Assembly.GetAssembly(typeof(string))
,它会加载 mscorlib.dll 中的类型,并且您提供的 linq 查询不会返回任何内容。您需要使用typeof(EmployeeMapping).Assembly
or加载程序集Assembly.GetAssembly(typeof(EmployeeMapping))
或Assembly.LoadFrom("YourAssemblyName.dll")
以查询该特定程序集的类型。
编辑:
要进一步回答您的问题...假设您知道负责映射的所有类型以及它们所包含的程序集。
protected void AutoMapperConfig()
{
const string mappingNamespace = "MyProject.Web.Core.Mappings";
//There are ways to accomplish this same task more efficiently.
var q = (from t in Assembly.LoadFrom("YourAssemblyName.dll").GetExportedTypes()
where t.IsClass && t.Namespace == mappingNamespace
select t).ToList();
//Assuming all the types in this namespace have defined a
//default constructor. Otherwise, this iterative call will
//eventually throw a TypeLoadException (I believe) because
//the arguments for any of the possible constructors for the
//type were not provided in the call to Activator.CreateInstance(t)
q.ForEach(t => Activator.CreateInstance(t));
}
但是,如果您在 Web 项目中引用程序集...如果在编译时类型未知,我将使用以下或某种 IoC/DI 框架来实例化映射类。
protected void AutoMapperConfig()
{
Mapper.CreateMap<Employee, EmployeeInfoViewModel>();
//Repeat the above for other "mapping" classes.
//Mapper.CreateMap<OtherType, OtherViewModel>();
}
编辑首先给出@Brendan Vogt 评论:
public interface IMappingHandler
{
}
//NOTE: None of this code was tested...but it'll be close(ish)..
protected void AutoMapperConfig()
{
//If the assemblies are located in the bin directory:
var assemblies = Directory.GetFiles(HttpRuntime.BinDirectory, "*.dll");
//Otherwise, use something like the following:
var assemblies = Directory.GetFiles("C:\\SomeDirectory\\", "*.dll");
//Define some sort of other filter...a base type for example.
var baseType = typeof(IMappingHandler);
foreach (var file in assemblies)
{
//There are other ways to optimize this query.
var types = (from t in Assembly.LoadFrom(file).GetExportedTypes()
where t.IsClass && !t.IsAbstract && baseType.IsAssignableFrom(t)
select t).ToList();
//Assuming all the queried types defined a default constructor.
types.ForEach(t => Activator.CreateInstance(t));
}
}