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