Activator.CreateInstance与通用存储库

Kri*_*ner 5 c# generics factory activator

我正在尝试(我认为)一个工厂,它根据传递给方法的枚举创建一个存储库.看起来像这样:

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)));
    }
}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

FormTypes

public enum FormTypes
{
    [EnumType(typeof(Form64_9C2Repository))]
    Form64_9C2,

    [EnumType(typeof(Form64_9BaseRepository))]
    Form64_9Base
}
Run Code Online (Sandbox Code Playgroud)

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

IEntity

public interface IEntity { }
Run Code Online (Sandbox Code Playgroud)

Form64_9C2(存根)

public class Form64_9C2 : IEntity { }
Run Code Online (Sandbox Code Playgroud)

将其全部称为:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是我type一直在努力解决null.我期待得到一个NotImplementedException,但我得到的ArgumentException是没有有效的formType.

在此输入图像描述

在实现IRepository<T>我的type/ repository成功创建之前(这里的工作代码),任何想法?我只是开始玩工厂,仿制药等等 - 所以如果我做错了什么,请指教!

Dar*_*rov 5

您的代码不能用于此行无法编译的完全相同的原因:

IRepository<IEntity> repo = new Form64_9C2Repository();
Run Code Online (Sandbox Code Playgroud)

即使是工具,基本上IRepository<IEntity>也不一样.IRepository<Form64_9C2>Form64_9C2IEntity

如果接口T上的泛型参数IRepositorycovariant:

public interface IRepository<out T> where T : class, IEntity
{
    IEnumerable<T> Read();    
}
Run Code Online (Sandbox Code Playgroud)

但不幸的是,这意味着它只能作为方法的返回类型出现,而不是作为参数出现.对于你和方法来说Update,这是不行的.你当然可以定义这样的结构:DeleteCreate

public interface IReadonlyRepository<out T> where T : class, IEntity
{
    IEnumerable<T> Read();    
}

public interface IRepository<T>: IReadonlyRepository<T> where T : class, IEntity
{
    bool Update(IEnumerable<T> entities);
    bool Delete(IEnumerable<T> entities);
    bool Create(IEnumerable<T> entities);
}
Run Code Online (Sandbox Code Playgroud)

让你的GetRepository方法返回一个IReadonlyRepository<IEntity>.

如果这对您不起作用,您将需要一个额外的参数来指定具体的实体类型,以便您执行正确的强制转换:

    public IRepository<TEntity> GetRepository<TEntity>(FormTypes formType) where TEntity: class, IEntity
    {
        // 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<TEntity> type = Activator.CreateInstance(typeToCreate) as IRepository<TEntity>;

        if (type != null)
            return type;

        throw new ArgumentException(string.Format("No repository found for {0}", nameof(formType)));
    }
}
Run Code Online (Sandbox Code Playgroud)

除了指定存储库类型之外,还需要指定实体类型:

var repo9c2 = factory.GetRepository<Form64_9C2>(FormTypes.Form64_9C2);
Run Code Online (Sandbox Code Playgroud)