Unity IoC:在没有构造函数依赖注入的情况下创建接口实例

Unity IoC : Create instance of an interface without constructor dependency injection

我对 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. 有什么方法可以不使用构造函数模式来传递存储库依赖性吗?

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

当您不向 class 添加构造函数时,C# 将在编译期间为您生成一个 public 无参数构造函数。这会导致 Unity 调用 'invisible' 无参数构造函数,这就是 none 私有字段被初始化的原因。

为防止此类意外编程错误,请始终确保在项目的属性构建选项卡中启用 "treat all warnings as errors"。这将确保编译器停止编译,因为它检测到这些未初始化的字段。

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

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