我有一个ASP .Net Web API控制器,我想要2个参数。第一个是EF上下文,第二个是缓存界面。如果我只是有EF上下文中的构造函数将被调用,但是当我添加了缓存界面我得到的错误:注入到带有2个参数的构造函数不起作用
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>();
}
我预计实体现在知道这两种类型的请求时,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;
}
是类注册意味着是一个单身?同时检查'IAppCache'实现'CachingService'以确保该类在初始化时不会抛出任何异常。该无参数异常是在尝试创建控制器时发生错误时的默认消息。 – Nkosi
什么是CachingService的依赖关系您提到它是第三方接口/类。它可能会请求容器不知道的依赖项。 – Nkosi
它使用MemoryCache.Default:https://github.com/alastairtree/LazyCache/blob/master/LazyCache/CachingService.cs – user441521