简体   繁体   中英

Unity IoC throws invalid cast exception

I'm trying to register a generic interface / implementation via Unity IoC, but the constructor parameter in the ViewModel, throws an invalid cast exception, and I cannot figure out why.

I have an interface, which all models implement:

public interface IEntity {}

A typical model would look like this:

public class Dashboard: IEntity { .... }

I have a database service, which can be of any model type, and an associated interface, for example:

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

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

The container registration looks like this:

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

which works up to this point.

However, when I try and load this into my ViewModel class, I get an invalid cast exception, my implementation on the constructor, for argument sake, in the DashboardPageViewModel, which looks like this:

private readonly IDbService<Dashboard> _dbService;

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

This throws the exception.

Why can I not cast Dashboard to in this regard? Trying to resolve the cast after I've registered the type, does not work either.

The class has been defined incorrectly.

In

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

DbService<T> only has type constraints where T is derived from IEntity and also IDbService<T>

You need to have the class derived from IDbService<T> interface and then apply the generic type constraint.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM