c# - 使用依赖注入通过构造函数初始化值
问题描述
我有一个UserService
实现接口的类IUserService
。
该类UserService
具有构造函数来初始化其参数的值。
我正在UserService
通过 DI 在另一个类中使用。
如何初始化 UserService 对象的值。
public class OfferService : IOfferService
{
private IUserService _userService;
private ISomeOtherService _someotherService;
public OfferService(IUserService userService, ISomeOtherService someotherService)
{
_userService = userService;
_someotherService = someotherService;
}
public bool SomeMethod()
{
string key = _someotherService.GetKey();
string value = _someotherService.GetValue();
//Calling parameterized constructor of UserService
var user = new UserService(key,value);
}
}
是否可以使用接口引用_userService
通过构造函数初始化值。
解决方案
处理这个问题的最简单方法是注入工厂而不是实例。这将允许您在运行时提供参数。
简单的工厂示例:
public interface IUserServiceFactory
{
IUserService GetUserService(string key, string val);
}
public class UserServiceFactory : IUserServiceFactory
{
public IUserService GetUserService(string key, string val)
{
return new UserService(key, val);
}
}
如何使用它:
public class OfferService : IOfferService
{
private IUserServiceFactory _userServiceFactory;
private ISomeOtherService _someotherService;
public OfferService(IUserServiceFactory userServiceFactory, ISomeOtherService someotherService)
{
_userServiceFactory = userServiceFactory;
_someotherService = someotherService;
}
public bool SomeMethod()
{
string key = _someotherService.GetKey();
string val = _someotherService.GetValue();
var user = _userServiceFactory.GetUserService(key, val);
return false;
}
}
看我的小提琴
推荐阅读
- java - 如何完成多线程编程问题
- unity3d - 贴花环绕网格
- android - Flutter - 如何调试原生android代码
- javascript - 关闭或打开javascript时如何显示
- python - Python - 阅读 Google Ads 关键字规划 .csv
- go - 如何找出选择器是在第一个还是最后一个位置
- maven - 在 Google Cloud SQL 环境中执行 maven 单元测试
- python - python中的aws cli和awcli驱动程序:如何设置端点?
- wordpress - 极慢的 WordPress 网站
- google-drive-api - 从服务器访问用户 Google Drive 文件