I would like to modify my current LetterFactory implementation and remove the call to Activator.CreateInstance with a call to the container to resolve the current Letter fully initialized with constructor injection. I have read the docs here and here, and even this SO Post while penning this post, but nothing seems to click.
Notes:
1) IDocumentServicesCore is an Aggregate.
2) All Letters are decorated with the LetterTypeAttribute (hundreds of them)
3) This LetterFactory itself is registered in the container.
public class LetterFactory : ILetterFactory
{
private readonly IDocumentServicesCore _documentServicesCore;
public LetterFactory(IDocumentServicesCore documentServicesCore)
{
_documentServicesCore = documentServicesCore;
}
public LetterBase Create(int letterId)
{
if (letterId <= 0)
{
throw new ArgumentOutOfRangeException(nameof(letterId));
}
List<Type> types = typeof(LetterBase).Assembly.GetTypes()
.Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(LetterBase)))
.ToList();
LetterBase letter = null;
foreach(Type type in types)
{
LetterTypeAttribute attribute = type.GetCustomAttributes<LetterTypeAttribute>().First();
if (!attribute.LetterId.Contains(letterId))
{
continue;
}
letter = Activator.CreateInstance(type, _documentServicesCore) as LetterBase;
break;
}
if (letter != null)
{
return letter;
}
string message = $"Could not find a LetterBase to create for id {letterId}.";
throw new NotSupportedException(message);
}
}
Update1
The problems seems to start with the fact that the letters themselves aren't registered, how to I take the LINQ code that collects the Letters from the assembly and register those enmass?
Thank you, Stephen