首页 > 解决方案 > Unity IoC:创建没有构造函数依赖注入的接口实例

问题描述

我对 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
    }
}

控制器正在调用此服务:

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存储库接口中的依赖关系,那么为什么我在那里得到空值?
  3. 有没有办法在不使用构造函数模式的情况下传递存储库依赖关系?

标签: c#dependency-injectionunity-container

解决方案


如果我注释掉 DashboardService 构造函数,我将得到空存储库对象。

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

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

有没有办法在不使用构造函数模式的情况下传递存储库依赖关系?

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


推荐阅读