【发布时间】:2017-04-05 07:06:03
【问题描述】:
我有一个 ASP .Net Web API 控制器,我想采用 2 个参数。第一个是 EF 上下文,第二个是缓存接口。如果我只有 EF 上下文,则调用构造函数,但是当我添加缓存接口时,会出现错误:
尝试创建类型控制器时出错 'MyV1 控制器'。确保控制器具有 无参数的公共构造函数。
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 函数发出请求时,Entity 现在知道这两种类型,它应该能够实例化一个实例,因为该构造函数采用它知道的类型,但事实并非如此。知道为什么吗?
[编辑]
请注意,我创建了自己的类 (IConfig) 并将其注册并将其添加到构造函数中并且它可以工作,但是每当我尝试将 IAppCache 添加到我的构造函数并向 API 发出请求时,我都会收到错误消息我它不能构造我的控制器类。我看到的唯一区别是 IAppCache 不在我的项目命名空间中,因为它是第 3 方类,但据我了解这并不重要。
这是 CachingService 的构造函数
public CachingService() : this(MemoryCache.Default) { }
public CachingService(ObjectCache cache) {
if (cache == null) throw new ArgumentNullException(nameof(cache));
ObjectCache = cache;
DefaultCacheDuration = 60*20;
}
【问题讨论】:
-
类注册是单例吗?还要检查
IAppCacheimplementationCachingService以确保该类在初始化时没有抛出任何异常。当尝试创建控制器时发生错误时,该无参数异常是默认消息。 -
CachingService的依赖关系是什么你提到它是一个 3rd 方接口/类。它可能正在请求容器不知道的依赖项。 -
它使用 MemoryCache。默认值:github.com/alastairtree/LazyCache/blob/master/LazyCache/…
-
只需在控制器中创建无参数构造函数,例如。公共 MyV1Controller() { }
标签: asp.net asp.net-web-api dependency-injection unity-container lazycache