簡體   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