c# – 使用2个参数注入构造函数不起作用
我有一个ASP .Net Web API控制器,我想要2个参数.第一个是EF上下文,第二个是缓存接口.如果我只有EF上下文,则构造函数被调用,但是当我添加缓存接口时,我得到错误:
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函数发出请求时,它应该能够实例化一个实例,因为该构造函数接受它知道的类型,但事实并非如此.知道为什么吗? [编辑] 以下是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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |