c# - 向 Unity IoC 注册 AccountController
问题描述
帐户控制器未正确注册
我有一个 ASP.NET MVC 应用程序,其中包含使用身份的个人用户帐户。在我的帐户控制器中,我有一个要注入的 UserMappingService。
有两个 AccountController 构造函数,一个最初是空的构造函数是导致问题的那个。我需要在这里注入 UserMappingService。在将服务添加到构造函数的参数之前,我可以通过将其添加到 UnityConfig.cs 来使控制器注册空构造函数
//parameterless constructor in AccountController.cs
public AccountController()
{
}
// From UnityConfig.cs in RegisterTypes method
container.RegisterType<AccountController>(new InjectionConstructor());
问题是,一旦我将服务添加为参数,就会出现错误。
private IUserMappingService userMappingService;
//constructor with interface in the parameter AccountController.cs
public AccountController(IUserMappingService mappingService)
{
userMappingService = mappingService;
}
//From UnityConfig.cs
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<IUserMappingService, UserMappingService>();
container.RegisterType<AccountController>(new InjectionConstructor());
}
运行时产生的错误是:RegisterType(Invoke.Constructor()) 中的错误 ArgumentException:未找到匹配的成员数据。
我很确定 (InjectionConstructor) 仅适用于默认的无参数构造函数,但我不知道在这种情况下如何注册控制器。
解决方案
您可以像这样指定依赖类型:
var ctr = new InjectionConstructor(typeof(IUserMappingService));
container.RegisterType<AccountController>(ctr);
或者您可以使用以下标记您的构造函数InjectionConstructorAttribute
:
[InjectionConstructor]
public AccountController(IUserMappingService mappingService)
{
userMappingService = mappingService;
}
推荐阅读
- jquery - $(this) 在 Ionic3 中不起作用
- javascript - CSS 画廊 - 如何更改 1 张照片
- ruby-on-rails - 显示和统计协会的协会
- javascript - 如何在javascript中手动触发“粘贴”事件?
- python - BeautifulSoup XML:通过兄弟元素的文本查找元素
- java - 无法向 API Retrofit 提交帖子
- javascript - 如何从由无序列表组成的菜单中从所选项目中获取值
- powershell - 由于特殊字符,Curl 命令在 powershell 中不起作用
- java - 如何使用 vertx 调用外部 API 并将数据返回给 java 对象
- c# - 为什么 Mono Develop(Unity) 会自行从脚本中删除我的自定义定义指令?