簡體   English   中英

Unity IoC引發無效的強制轉換異常

[英]Unity IoC throws invalid cast exception

我正在嘗試通過Unity IoC注冊通用接口/實現,但是ViewModel中的構造函數參數拋出了無效的強制轉換異常,我無法弄清原因。

我有一個接口,所有模型都可以實現:

public interface IEntity {}

典型模型如下所示:

public class Dashboard: IEntity { .... }

我有一個數據庫服務,它可以是任何模型類型,以及一個關聯的接口,例如:

public interface IDbService<T> where T: IEntity { .... }

public class DbService<T> where T : IEntity, IDbService<T> { .... }

容器注冊如下所示:

container.RegisterType(typeof(IDbService<>), typeof(DbService<>));

到現在為止。

但是,當我嘗試將其加載到ViewModel類中時,在DashboardPageViewModel中,出於參數考慮,我得到了一個無效的強制轉換異常,即構造函數上的實現,如下所示:

private readonly IDbService<Dashboard> _dbService;

public DashboardPageViewModel(IDbService<Dashboard> dbService)
{
     _dbService = dbService;
}

這引發異常。

為什么我不能在這方面投放資訊主頁? 在注冊類型后嘗試解析類型轉換,也不起作用。

該類定義不正確。

public class DbService<T> where T : IEntity, IDbService<T> { .... }

DbService<T>僅具有類型約束,其中T衍生自IEntity以及IDbService<T>

您需要具有從IDbService<T>接口派生的類,然后應用通用類型約束。

public interface IDbService<T> where T: IEntity { .... }

public class DbService<T> : IDbService<T> where T : IEntity { .... }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM