[英]Creating an Interface for an Entity Framework Core DbContext so that it can be injected/tested?
[英]Creating a DbContext with custom constructor with injected parameter in Entity Framework
我正在使用代碼優先數據庫,但是當我嘗試執行“ Update-Database”時,出現以下錯誤。
The target context 'AllMid.DL.Repository.Implementation.AllMidContext' is not constructible.
Add a default constructor or provide an implementation of IDbContextFactory.
現在對我來說很明顯,問題是我沒有默認的構造函數或IDbContextFactory接口的實現,但是在示例項目中,我看到的是沒有這樣做。 有人知道該怎么做嗎?
我目前有一個與此類似的DbContext。
internal class AllMidContext : DbContext, IAllMidContext
{
public DbSet<TreeEntity> Tree { get; set; }
public AllMidContext(IConfigurationAccess configAccess) : base(configAccess.GetDefaultConnectionString())
{
}
}
configAccess應該由結構映射注入。
和像這樣的DataContextAccess類
internal class DataContextAccess : IDataContextAccess
{
private readonly IConfigurationAccess _configAccess;
public DataContextAccess(IConfigurationAccess configAccess)
{
_configAccess = configAccess;
}
public IAllMidContext GetAllMidContext()
{
return new AllMidContext(_configAccess);
}
}
現在的問題是,有沒有默認構造函數或工廠的方法嗎? 我的依賴項注入將始終輸入參數,因此如何使EF使用我的自定義構造函數?
我相信update-database
正在尋找沒有輸入的構造函數。 您可以做的是編寫一個沒有輸入的構造函數,然后在其主體中進行注入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.