我有一個業務邏輯組件以下實現一個通用的接口:實例化一個類使用反射
public class BusinessEntity
{
...
}
public class Customer : BusinessEntity
{
...
}
public interface IEntityManager <T> where T : BusinessEntity
{
T SaveData(T oData);
}
public CustomerEntityManager : IEntityManager <Customer>
{
Customer SaveData(Customer o)
{
...
}
}
我不得不來加載上面的組件(由於幾個明顯的原因),在我目前的項目通過反思和實例化CustomersEntityManager
。想象一下,我寫的方法如下:
public class EntityFactory
{
public static IEntityManager<BusinessEntity> GetManagerInstance(string EntityName)
{
var asm = GetAssembly(); // imagine that I loaded the assembly somehow
EntityName = "Customer"; // just imagine
object o;
// DO NOT KNOW WHAT TO WRITE HERE.
return o as IEntityManager<BusinessEntity>; // this needs to be an instance of CustomerEntityManager.
}
}
我可以選擇修改業務程序集。但實例創建需要在我當前的項目中,我必須使用反射來加載業務程序集。所有的數據類型只有在運行時纔會知道。
我可能會錯過一些根本性的東西,或者可能做錯了編碼。請幫我解決這個問題。
UPDATE:
遵循 「德里斯」 的建議,像以下:
string fullTypeName = "Your.Namespace." + EntityName + "EntityManager";
object o = Activator.CreateInstance(asm.FullName, fullTypeName);
看起來它創建的實例。然而,它結束了一個錯誤:
Cannot cast 'o' (which has an actual type of 'CustomerEntityManager') to 'IEntityManager'
時得到執行以下語句:
return o as IEntityManager<BusinessEntity>
感謝
+1 for IoC Framework – smartcaveman
driis,我得到錯誤當語句「return o as IEntityManager」時,無法將'o'(具有'CustomerEntityManager'的實際類型)轉換爲'IEntityManager '正在執行。 –
user203687
你不想要IEntityManager?因爲這是CustomerEntityManager實現的。 –
driis