What would be the most efficient way to instanciate an object according to a generic type passed to a Factory class, for instance:
public class LoggerFactory
{
public static ILogger<T> Create<T>()
{
// Switch Statement?
// Generic Dictionary?
// EX.: if "T" is of type "string": return (ILogger<T>)new StringLogger();
}
}
How would you do it? Which branching statement? etc…
I think it’s best to keep it simple, perhaps something like this:
You just call the
AddLoggerProviderfor each type you want to support, can be extended at runtime, it ensures you definetly add an implementation of the interface to the library and not some object, isn’t very fast because of theActivator, but creating a logger wont likely be a bottleneck anyway. Hope it looks okay.Usage:
Note: each
ILogger<T>requires a parameterless constructor for theActivator, but that too is ensured with thenew()generic constraint in the add method.