asp.net - 使用 2 个参数注入(inject)构造函数不起作用

标签 asp.net asp.net-web-api dependency-injection unity-container lazycache

我有一个 ASP .Net Web API Controller ,我想使用 2 个参数。第一个是 EF 上下文,第二个是缓存接口(interface)。如果我只有 EF 上下文,构造函数就会被调用,但是当我添加缓存接口(interface)时,我会收到错误消息:

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 的请求我收到错误消息,告诉我它无法构建我的 Controller 类。我看到的唯一区别是 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; 
}

最佳答案

检查 IAppCache 实现 CachingService 以确保该类在初始化时没有抛出任何异常。该无参数异常是在尝试创建 Controller 时发生错误时的默认消息。这不是一个非常有用的异常,因为它不能准确指示发生的真正错误是什么。

您提到它是第 3 方接口(interface)/类。它可能正在请求容器不知道的依赖项。

引用 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了解更多详情。

关于asp.net - 使用 2 个参数注入(inject)构造函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40727756/

相关文章:

c# - MVVM Light 按键注册界面

java - 我可以使用带有构造函数和本地实例的 Guice 抽象模块来提供动态绑定(bind)吗?

asp.net - 如何延长 session 超时时间?

c# - 部分工作完成两次(ThreadPool.QueueUserWorkItem)

javascript - Angular 针对 Asp.Net WebApi,在服务器上实现 CSRF

jquery - 如何编写菜单 ul li a 的 Click 函数?

.NET IoC : Configure library components from (application) composition root

c# - Page_Load、Page_PreInit 和 Page_OnInit

asp.net - 无法从 web.config 引用自定义事件

asp.net-mvc-4 - 计算请求应该是 GET 还是 POST?