You really haven't defined what you mean by "better." However, one way I can do this is to create a custom attribute for each TClass that defines the repository, and read that attribute in your method GetRepository. It uses some reflection, but it is more elegant than a large if-else, and lighter than a full injection environment. Quick example:
Attribute
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class RepositoryAttribute : Attribute
{
public RepositoryAttribute(Type repositoryType)
{
this.RepositoryType = repositoryType;
}
public Type RepositoryType { get; private set; }
}
Entity Class:
[Repository(typeof(UserClassRepository))]
public class UserClass
{
}
Factory Method:
public static IBaseRepository<TClass> GetRepository<TClass>()
where TClass : IDataEntity
{
Type t = typeof(TClass);
RepositoryAttribute attr =
(RepositoryAttribute)Attribute.GetCustomAttribute(t,
typeof(RepositoryAttribute), false);
if (attr != null)
{
return (IBaseRepository<TClass>)Activator.CreateInstance(attr.RepositoryType);
}
return null;
}
source
share