![](/img/trans.png)
[英]Activator.CreateInstance failing with 'No parameterless constructor'
[英]Activator.CreateInstance - parameterless constructor issue
我正在嘗試從具有EntityTypeConfiguration(實體框架主義)基礎的程序集中動態提取類型。 在擁有所有類型之后,我想為每個實例化一個對象並將其傳遞給生成器(DbModelBuilder)函數。
范例類別:
public class LocationConfiguration : EntityTypeConfiguration<Location>
{
public LocationConfiguration()
{
// some basic stuff here
}
}
我得到的類型沒有問題,但是在這一行出現了無參數的構造函數錯誤:
var result = (dynamic)Activator.CreateInstance(type);
PS我理解在這個特定示例中,我可以只使用AddFromAssembly(),但最終我想選擇加載的配置。
編輯:
添加引發錯誤的行的硬編碼示例:
var result = (dynamic)Activator.CreateInstance(typeof(LocationConfiguration));
編輯#2:
System.MissingMethodException occurred
HResult=0x80131513
Message=No parameterless constructor defined for this object.
Source=mscorlib
StackTrace:
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at .OnModelCreating(DbModelBuilder builder) in C:\Development\Context.cs:line 25
at System.Data.Entity.Internal.LazyInternalContext.CreateModelBuilder()
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
如果以下代碼是您問題的准確復制,則答案為“因為EntityTypeConfiguration
在其自己的構造函數中創建了Location
的實例”。
using System;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
object thing = Activator.CreateInstance<PublicCtorClass>();
}
}
class PublicCtorClass : ProtectedCtorGenericClass<PublicParameterisedCtorClass>
{
public PublicCtorClass() { }
}
class ProtectedCtorGenericClass<T>
{
protected ProtectedCtorGenericClass()
{
object thing = Activator.CreateInstance(typeof(T));
}
}
class PublicParameterisedCtorClass
{
public PublicParameterisedCtorClass(object arg) { }
}
}
在那種情況下,解決方案將是創建EntityTypeConfiguration的子類並向其添加通用約束,該約束將其限制為new()
。 像這樣:
class ActivatorSafeEntityTypeConfiguration<T> : EntityTypeConfiguration<T> where T : new()
{
}
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.