c# - 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;
问题:
- 截至目前,我的代码运行良好,但如果我注释掉
DashboardService
构造函数,我将得到空存储库对象。 - 我正在解决
Unity
存储库接口中的依赖关系,那么为什么我在那里得到空值? - 有没有办法在不使用构造函数模式的情况下传递存储库依赖关系?
解决方案
如果我注释掉 DashboardService 构造函数,我将得到空存储库对象。
当您不向类添加构造函数时,C# 将在编译期间为您生成一个公共无参数构造函数。这会导致 Unity 调用那个“不可见”的无参数构造函数,这就是为什么你的私有字段都没有被初始化的原因。
为防止此类意外编程错误,请始终确保在项目的属性构建选项卡中启用“将所有警告视为错误”。这将确保编译器停止编译,因为它检测到这些未初始化的字段。
有没有办法在不使用构造函数模式的情况下传递存储库依赖关系?
是的,但是您可以使用的所有其他方法都会导致代码异味或反模式。构造函数注入几乎在所有情况下都是最好的解决方案。
推荐阅读
- javascript - Material Design Lite - JS 不应用事件监听器
- javascript - 登录后反应重定向不起作用
- docker - 部署后,一个 Rancher 负载均衡的 RESTful 应用实例返回 404,而其他返回结果
- php - 使用 PHP 和 MySQL 更新记录中的 BLOB
- lucene - Azure 搜索中的模糊搜索和邻近搜索
- html - 我希望我的表连接在顶部(css / html)
- javascript - 在ajax中回击两次成功
- python - 将 .gif 文件从 4d numpy 数组生成到内存流中
- java - 获取锁屏壁纸安卓
- javascript - 画布在 React.js 中无法正确缩放