我的WebApi控制器(MenusController)无法使用错误消息“实例化List`1具有多个长度为1的构造函数”进行实例化。依赖图:我使用Unity进行依赖注入。
MenusController> IMenuService> IMenuRepository> IEntitiesDBContext
这里的所有类,除了接收两个的MenuRepository之外还有1个依赖。
public class MenuRepository : IMenuRepository
{
IMonopolyEntitiesDbContext _dbContext;
List<MenuLink> _allsubMenus;
public MenuRepository(IMonopolyEntitiesDbContext context, List<MenuLink> allsubMenus)
{
_dbContext = context;
_allsubMenus = allsubMenus;
}
//Additional Code.
}
public partial class MonopolyEntities : DbContext, IMonopolyEntitiesDbContext
{
public MonopolyEntities()
: base("name=MonopolyEntities")
{
}
}
Unity注册
public static class WebApiHelper
{
public static void RegisterWebApiTypes(IUnityContainer container)
{
container.RegisterType<IMenuServices, MenuServices>(new PerThreadLifetimeManager());
container.RegisterType<MenuLink>();
container.RegisterType<IList<MenuLink>>(new InjectionFactory( x => new List<MenuLink>()));
container.RegisterType<IMonopolyEntitiesDbContext, MonopolyEntities>(new PerThreadLifetimeManager());
container.RegisterType<IMenuRepository, MenuRepository>(new PerThreadLifetimeManager(), new InjectionConstructor(typeof(IMonopolyEntitiesDbContext), typeof(List<MenuLink>)));
}
}
这是堆栈跟踪
依赖项的解析失败,type =“Monopoly.WebApi.MenusController”,name =“(none)”。在解决时发生异常:例外是:InvalidOperationException - 类型List 1 has multiple constructors of length 1. Unable to disambiguate. ----------------------------------------------- At the time of the exception, the container was: Resolving Monopoly.WebApi.MenusController,(none) Resolving parameter "menuServices" of constructor Monopoly.WebApi.MenusController(Monopoly.BLL.Interfaces.IMenuServices menuServices) Resolving Monopoly.BLL.MenuServices,(none) (mapped from Monopoly.BLL.Interfaces.IMenuServices, (none)) Resolving parameter "repository" of constructor Monopoly.BLL.MenuServices(Monopoly.DAL.Interfaces.IMenuRepository repository) Resolving Monopoly.DAL.MenuRepository,(none) (mapped from Monopoly.DAL.Interfaces.IMenuRepository, (none)) Resolving parameter "allsubMenus" of constructor Monopoly.DAL.MenuRepository(Monopoly.DAL.Interfaces.IMonopolyEntitiesDbContext context, System.Collections.Generic.List
1 [[Monopoly.DAL.MenuLink,Monopoly,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]] allsubMenus)Resolving System.Collections.Generic.List` 1 [Monopoly.DAL.MenuLink],(无)
我知道有两个构造函数的参数列表长度相等会产生歧义,在这种情况下我需要显式选择要使用的构造函数。但我这里没有一个有超过1个构造函数的类型。
任何想法?
答案 0 :(得分:2)
您的类需要类型为GetContent
的参数,但您的Unity容器只能注册接口List<MenuLink>
。
将IList<MenuLink>
作为构造函数参数对我来说并不是很合适,但如果这是你想要的,我建议更改你的存储库构造函数来取代接口而不是类。 Unity应该能够使用List<>
构建它来提供:
InjectionFactory
和(我认为)
public MenuRepository(IMonopolyEntitiesDbContext context, IList<MenuLink> allsubMenus)
{
_dbContext = context;
_allsubMenus = allsubMenus;
}