繁体   English   中英

在运行时创建未知类型的通用存储库

[英]Create generic repository of unknown type at run-time

我在这里快死了,尝试用我的工作单元实现一个通用的存储库。 这将与我正在处理的特定项目很好地配合。 但是我只是无法掌握正确的语法。 如果我只能让以下内容作为起点...

我希望能够

unit_of_work.Repository<don't-know-until-runtime>().Insert(run-time-object);

在运行时我不知道要处理哪种对象,我只知道它将是'BaseClass'类型的。

非常感谢您的帮助。 我试图将代码整理如下。

public class BaseClass
{
}

public class SubClass1 : BaseClass
{
    public SubClass1()
        : base()
    {
    }
}

public interface IRepository<TEntity> where TEntity : class
{
    void Insert(TEntity entity);
}


public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
    public void Insert(TEntity entity)
    {
        System.Diagnostics.Debug.WriteLine("got here!!");
    }
}

public class UnitOfWork
{
    public virtual IRepository<TEntity> Repository<TEntity>() where TEntity : class
    {
        var type = typeof(TEntity).Name;
        var repositoryType = typeof(Repository<>);

        return (IRepository<TEntity>) Activator.CreateInstance(repositoryType.MakeGenericType(typeof(TEntity)));
    }
}

class Program
{
    static void Main(string[] args)
    {
        UnitOfWork unit_of_work = new UnitOfWork();

        SubClass1 testClass1 = new SubClass1();

        // this works fine, when I know the type in advance...
        unit_of_work.Repository<SubClass1>().Insert(testClass1);

        // ... but when I don't know the type, then what?
        // (All I know is that the incoming object will be of type BaseClass)
    }
}

只需使用BaseClass的必要类型约束声明存储库和UoW方法:

public interface IRepository<TEntity> where TEntity : BaseClass
...
public class Repository<TEntity> : IRepository<TEntity> where TEntity : BaseClass
...
public virtual IRepository<TEntity> Repository<TEntity>() where TEntity : BaseClass

然后您可以执行以下操作:

unit_of_work.Repository<BaseClass>().Insert(<whatever>);

这是因为通用的逆差而起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM