Ich benutze auch ein Bootstrap-Programm diese Art der Sache Start Aufgabe zu bewältigen. Eigentlich benutze ich eine Kette von Bootstrappern, weil ich so verrückt bin. Automapperweise fanden wir, dass es viel sauberer war, einige AutoMappingBuddy-Klassen zu erstellen und sie mit einem Attribut zu dekorieren. Wir verkabeln die Mapper dann über einige Reflektionsaufrufe (nicht billig, aber sie feuern nur einmal auf der Stelle). Diese Lösung wurde entdeckt, nachdem wir es satt hatten, ein AutoMapper-Problem in Zeile 841 einer Datei mit mehr als 1200 Zeilen zu finden.
Ich dachte über das Posten des Codes, aber ich kann es wirklich nicht so purdy nennen. Wie auch immer, hier geht:
Zuerst eine einfache Schnittstelle für die AutoMappingBuddies:
public interface IAutoMappingBuddy
{
void CreateMaps();
}
Zweitens ein wenig Attribut etwas Klebstoff zu bieten:
public class AutoMappingBuddyAttribute : Attribute
{
public Type MappingBuddy { get; private set; }
public AutoMappingBuddyAttribute(Type mappingBuddyType)
{
if (mappingBuddyType == null) throw new ArgumentNullException("mappingBuddyType");
MappingBuddy = mappingBuddyType;
}
public IAutoMappingBuddy CreateBuddy()
{
ConstructorInfo ci = MappingBuddy.GetConstructor(new Type[0]);
if (ci == null)
{
throw new ArgumentOutOfRangeException("mappingBuddyType", string.Format("{0} does not have a parameterless constructor."));
}
object obj = ci.Invoke(new object[0]);
return obj as IAutoMappingBuddy;
}
}
Drittens die AutoMappingEngine. Es ist, wo die Magie passiert:
public static class AutoMappingEngine
{
public static void CreateMappings(Assembly a)
{
Dictionary<Type, IAutoMappingBuddy> mappingDictionary = GetMappingDictionary(a);
foreach (Type t in a.GetTypes())
{
var amba =
t.GetCustomAttributes(typeof (AutoMappingBuddyAttribute), true).OfType<AutoMappingBuddyAttribute>().
FirstOrDefault();
if (amba!= null && !mappingDictionary.ContainsKey(amba.MappingBuddy))
{
mappingDictionary.Add(amba.MappingBuddy, amba.CreateBuddy());
}
}
foreach (IAutoMappingBuddy mappingBuddy in mappingDictionary.Values)
{
mappingBuddy.CreateMaps();
}
}
private static Dictionary<Type, IAutoMappingBuddy> GetMappingDictionary(Assembly a)
{
if (!assemblyMappings.ContainsKey(a))
{
assemblyMappings.Add(a, new Dictionary<Type, IAutoMappingBuddy>());
}
return assemblyMappings[a];
}
private static Dictionary<Assembly, Dictionary<Type, IAutoMappingBuddy>> assemblyMappings = new Dictionary<Assembly, Dictionary<Type, IAutoMappingBuddy>>();
}
Kinda zusammen in einer Stunde geschlagen oder so, es gibt wahrscheinlich elegantere Wege dorthin zu gelangen.
Danke Jimmy! Hervorragende Arbeit an diesem Tool, es rockt auf mehreren Ebenen. Ich mag die Flagge auf dem Bootstrapper. Ich werde das heute Abend in meinen Code stecken. – KevDog
Danke! Das hat mir sehr geholfen. Wie für das Werkzeug ist es sehr mächtig, ich liebe es! – Rushino