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; }解决方法 检查IAppCacheimplementation CachingService以确保该类在初始化时不会抛出任何异常.尝试创建控制器时发生错误时,该无参数异常是默认消息.它不是一个非常有用的例外,因为它没有准确地指出发生了什么真正的错误.
你提到它是第三方接口/类.它可能是请求容器不知道的依赖项.
参考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.
总结以上是内存溢出为你收集整理的c# – 使用2个参数注入构造函数不起作用全部内容,希望文章能够帮你解决c# – 使用2个参数注入构造函数不起作用所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)