I have a website that is using the following code to return a repository, it will accept an interface and return the firt implementation it finds, however, I think the code is too slow and causing issues, is there any better ways to implement this?
Thanks
public T For<T>() where T : class
{
T returnVar = null;
Assembly asm = Assembly.GetExecutingAssembly();
var types = asm.GetTypes().Where(x => x.IsClass == true && x.Namespace != null && x.Namespace.StartsWith("Website.Core.Data.Repositories"));
var result = types.Where(x => x.GetInterface(typeof(T).Name) != null);
foreach (var x in result)
{
var mi = x.GetConstructors();
returnVar = (T)asm.CreateInstance(x.UnderlyingSystemType.ToString());
}
if (returnVar != null)
return returnVar;
else
throw new Exception("No Repository for: " + typeof(T).Name);
}
How about this: