gpt4 book ai didi

c# - 带有默认构造函数的 Unity Framework IoC

转载 作者:太空狗 更新时间:2023-10-29 17:31:47 24 4
gpt4 key购买 nike

我正在尝试像这样向我的 MVC Controller 注入(inject)依赖性

private static void RegisterContainer(IUnityContainer container)
{
container
.RegisterType<IUserService, UserService>()
.RegisterType<IFacebookService, FacebookService>();
}

UserService 类有一个这样的构造函数...

public UserService(): this(new UserRepository(), new FacebookService())
{
//this a parameterless constructor... why doesnt it get picked up by unity?
}

public UserService(IUserRepository repository, IFacebookService facebook_service)
{
Repository=repository;
this.FacebookService=facebook_service;
}

我得到的异常如下...

The current type, Repositories.IUserRepository, is an interface and cannot be constructed. Are you missing a type mapping?

它看起来像是在尝试向服务中注入(inject)一个构造函数,但默认值就足够了吗?为什么它不映射到无参数构造函数?

最佳答案

Unity 默认约定(在文档中清楚地说明)是选择具有最多参数的构造函数。你不能笼统地说“IoC 不会找到最具体的构造函数,如果你在注册类型时不指定构造函数参数,它会自动调用默认构造函数。”每个容器实现可以并且确实有不同的默认值。

在 Unity 的情况下,就像我说的,它将选择参数最多的构造函数。如果有两个拥有最多的参数,那么它就会有歧义并抛出。如果您想要不同的东西,您必须配置容器来做到这一点。

您的选择是:

将 [InjectionConstructor] 属性放在要调用的构造函数上(不推荐,但快速简便)。

使用 API:

container.RegisterType<UserService>(new InjectionConstructor());  

使用 XML 配置:

<container>
<register type="UserService">
<constructor />
</register>
</container>

关于c# - 带有默认构造函数的 Unity Framework IoC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3714357/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com