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

标签 c# dependency-injection unity-container

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

相关文章:

c# - 索引超出数组错误的范围 (C#)

java - 使用Guice,如何提供同一类型的不同实例?

c# - ASP.NET MVC + Unity 2.0 : lazy loading dependency properties?

inversion-of-control - Unity 框架入门

c# - Unity Container RegisterType<TFrom, TTo> 问题

c# - 将 ACE OLEDB 12 驱动程序包含在 clickOnce 安装中

c# - 通过 C# 应用程序将图像保存在 MySQL 中

c# - 有没有办法结合 LINQ 和异步

dependency-injection - 依赖注入(inject)和/vs 全局单例

c# - 获取 .net 核心中注入(inject)服务的调用方信息