我想玩弄(我认为是)一个工厂,根据传递给该方法的枚举创建一个存储库。看起来是这样的:Activator.CreateInstance与一个通用的存储库
RepositoryFactory
public class RepositoryFactory
{
public IRepository<IEntity> GetRepository(FormTypes formType)
{
// Represents the IRepository that should be created, based on the form type passed
var typeToCreate = formType.GetAttribute<EnumTypeAttribute>().Type;
// return an instance of the form type repository
IRepository<IEntity> type = Activator.CreateInstance(typeToCreate) as IRepository<IEntity>;
if (type != null)
return type;
throw new ArgumentException(string.Format("No repository found for {0}", nameof(formType)));
}
}
IRepository
public interface IRepository <T>
where T : class, IEntity
{
bool Create(IEnumerable<T> entities);
IEnumerable<T> Read();
bool Update(IEnumerable<T> entities);
bool Delete(IEnumerable<T> entities);
}
FormTypes
public enum FormTypes
{
[EnumType(typeof(Form64_9C2Repository))]
Form64_9C2,
[EnumType(typeof(Form64_9BaseRepository))]
Form64_9Base
}
EnumExtensions
public static class EnumExtensions
{
/// <summary>
/// Get the Enum attribute
/// </summary>
/// <typeparam name="T">The attribute</typeparam>
/// <param name="enumValue">The enum</param>
/// <returns>The type to create</returns>
public static T GetAttribute<T>(this System.Enum enumValue)
where T : Attribute
{
FieldInfo field = enumValue.GetType().GetField(enumValue.ToString());
object[] attribs = field.GetCustomAttributes(typeof(T), false);
T result = default(T);
if (attribs.Length > 0)
{
result = attribs[0] as T;
}
return result;
}
}
Form64_9C2Repository
public class Form64_9C2Repository : IRepository<Form64_9C2>
{
public bool Create(IEnumerable<Form64_9C2> entities)
{
throw new NotImplementedException();
}
public bool Delete(IEnumerable<Form64_9C2> entities)
{
throw new NotImplementedException();
}
public IEnumerable<Form64_9C2> Read()
{
throw new NotImplementedException();
}
public bool Update(IEnumerable<Form64_9C2> entities)
{
throw new NotImplementedException();
}
}
IEntity
public interface IEntity { }
Form64_9C2(存根)
public class Form64_9C2 : IEntity { }
调用一切为:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Repository Factory Example \n\n");
Business.Factory.RepositoryFactory factory = new Business.Factory.RepositoryFactory();
// Get a 64 9C2 repository
var repo9c2 = factory.GetRepository(FormTypes.Form64_9C2);
Console.WriteLine(repo9c2);
}
}
我的问题是我的type
总是解决到null
。我期待得到一个NotImplementedException
,但我相反得到ArgumentException
没有一个有效的formType。
此前实施IRepository<T>
我type
/repository
已成功创建(工作代码here),任何想法?我只是开始玩弄工厂,仿制药等 - 所以如果我在做一些错误的方式,请告诉我!
哇,只是让'出T'变化很大 - 尽管我真的不明白为什么:(不幸的是我希望能够解决存储库的所有CRUD ,而不仅仅是我看到你提供了一个这样做的方式,但通过添加一个additio最终参数。我真的希望将我的存储库及其关联的实体保留在一起,以避免调用具有冲突实体的某个存储库。感谢+1,我马上会接受,假设我没有发现更类似于我真正希望完成的事情。 – Kritner