当我从 Ioc 配置中使用时,我得到关于错误(不能用作泛型类型或方法中的类型参数 'TTo')

When I Use from Ioc Configuration I Get Error About (cannot be used as type parameter 'TTo' in the generic type or method )

当我在 Web API 项目中使用 UnityResolver 时,我收到关于使用通用 Class 或接口的错误。例如,我的 IPersonRepository 使用 IBaseRepository,我的 PersonRepository Class 使用 BaseRepository。现在,我想注册这些 类 以应用 IoC .

我的IPersonRepository界面是

public interface IPersonRepository : IBaseRepository<Person>
{
}

我的 PersonRepository Class 是

public class PersonRepository : BaseRepository<Person>
{
    public PersonRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
    {
    }
}

现在我使用 from UnityContainer 用下面的代码注册它。

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services
    var container = new UnityContainer();
    container.RegisterType<IPersonRepository, PersonRepository>(new HierarchicalLifetimeManager());
    config.DependencyResolver = new UnityResolver(container);

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

但是我得到了这个错误。

Severity Code Description Project File Line Suppression State Error CS0311 The type 'RepositoryTest.Repository.PersonRepository' cannot be used as type parameter 'TTo' in the generic type or method 'UnityContainerExtensions.RegisterType<TFrom, TTo>(IUnityContainer, LifetimeManager, params InjectionMember[])'. There is no implicit reference conversion from 'RepositoryTest.Repository.PersonRepository' to 'RepositoryTest.IRepository.IPersonRepository'.

如何解决?

PersonRepository 也需要从接口中导出它们才能关联。

PersonRepository Class 应该是...

public class PersonRepository : BaseRepository<Person>, IPersonRepository {
    public PersonRepository(IUnitOfWork unitOfWork) : base(unitOfWork) {
        //...
    }
}

因为必须有从实现到抽象的隐式引用转换。

这就是错误消息告诉您的内容。