AccountController中注册使用Unity的IoC

问题描述 投票:1回答:1

账户控制器没有正确注册

我有使用Identity个人用户帐户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)仅用于默认参数的构造函数好,但我不知道该怎么注册在这种情况下,控制器。

c# asp.net-mvc unity-container ioc-container
1个回答
0
投票

您可以规范依赖型是这样的:

var ctr = new InjectionConstructor(typeof(IUserMappingService));
container.RegisterType<AccountController>(ctr);

或者你可以国旗InjectionConstructorAttribute构造函数:

[InjectionConstructor]
public AccountController(IUserMappingService mappingService)
{
     userMappingService = mappingService;
}
© www.soinside.com 2019 - 2024. All rights reserved.