An error occurred when trying to create a controller of type
‘MyV1Controller’. Make sure that the controller has a
parameterless public constructor.@H_403_6@
private MyEntities dbContext; private IAppCache cache; public MyV1Controller(MyEntities ctx,IAppCache _cache) { dbContext = ctx; cache = _cache; }
我的UnityConfig.cs@H_403_6@
public static void RegisterTypes(IUnityContainer container) { // TODO: Register your types here container.RegisterType<MyEntities,MyEntities>(); container.RegisterType<IAppCache,CachingService>(); }
我希望Entity现在知道两种类型,当为MyV1Controller函数发出请求时,它应该能够实例化一个实例,因为该构造函数接受它知道的类型,但事实并非如此.知道为什么吗?@H_403_6@
[编辑]
请注意,我创建了自己的类(IConfig)并将其注册并将其添加到构造函数中并且它工作正常,但每当我尝试将IAppCache添加到构造函数并向API发出请求时,我会收到错误告诉我它可以’构造我的控制器类.我看到的唯一区别是IAppCache不在我的项目命名空间中,因为它是第三方类,但这应该与我的理解无关.@H_403_6@
以下是CachingService的构造函数@H_403_6@
public CachingService() : this(MemoryCache.Default) { } public CachingService(ObjectCache cache) { if (cache == null) throw new ArgumentNullException(nameof(cache)); ObjectCache = cache; DefaultCacheDuration = 60*20; }
解决方法
你提到它是第三方接口/类.它可能是请求容器不知道的依赖项.@H_403_6@
参考Unity Framework IoC with default constructor@H_403_6@
Unity正在使用大多数参数调用构造函数,在本例中是…@H_403_6@
public CachingService(ObjectCache cache) { ... }
由于容器对ObjectCache一无所知,它将传入null,根据构造函数中的代码将抛出异常.@H_403_6@
更新:@H_403_6@
从评论中添加此内容,因为它可以证明对其他人有用.@H_403_6@
container.RegisterType<IAppCache,CachingService>(new InjectionConstructor(MemoryCache.Default));
有关详细信息,请参阅此处Register Constructors and Parameters.@H_403_6@