gpt4 book ai didi

c# - 统一 IoC : Create instance of an interface without constructor dependency injection

转载 作者:太空宇宙 更新时间:2023-11-03 22:40:18 25 4
gpt4 key购买 nike

我对 Unity 和 DI 术语有点陌生,因此想了解它是如何工作的。我有以下使用 Unity 容器实现 DI 的代码。

public class DashboardService: IDashboardService
{
private readonly IRepository<USERROLE> repoUserRole;
private readonly IRepository<INSTITUTION> repoInstitution;

public DashboardService(
IRepository<USERROLE> repoUserRole, IRepository<INSTITUTION> repoInstitution)
{
this.repoUserRole = repoUserRole;
this.repoInstitution = repoInstitution;
}

public List<USERROLE> GET(List<string> Id)
{
// Use repoUserRole object to get data from database
}
}

Controller 正在调用此服务:

public class DashboardController : ApiController
{
private readonly IDashboardService dashboardService;

public DashboardController(IDashboardService dashboardService)
{
this.dashboardService = dashboardService;
this.mapper = mapper;
}

//Action method which uses dashboardService object
}

这是 Unity 配置:

var container = new UnityContainer();

container.RegisterType(typeof(IDashboardService), typeof(DashboardService))
.RegisterType(typeof(IRepository<>), typeof(Repository<>));

return container;

问题:

  1. 截至目前,我的代码运行良好,但如果我注释掉 DashboardService 构造函数,我将获得空存储库对象。
  2. 我正在 Unity 中解决存储库接口(interface)的依赖关系,那么为什么我在那里得到 null?
  3. 有什么方法可以不使用构造函数模式来传递存储库依赖性吗?

最佳答案

if I comment out the DashboardService constructor, I am getting the null repository objects.

当你不给类添加构造函数时,C#会在编译时为你生成一个公共(public)的无参构造函数。这会导致 Unity 调用那个“不可见的”无参数构造函数,这就是为什么您的私有(private)字段都没有被初始化的原因。

为防止此类意外编程错误,请始终确保在项目的属性构建选项卡中启用“将所有警告视为错误”。这将确保编译器停止编译,因为它检测到这些未初始化的字段。

Is there any way to pass the repository dependancy without using the constructor pattern?

是的,但是您可以使用的所有其他方法都会导致代码异味或反模式。构造函数注入(inject)几乎在所有情况下都是最佳解决方案。

关于c# - 统一 IoC : Create instance of an interface without constructor dependency injection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52563229/

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