统一解析嵌套构造函数
本文关键字:嵌套 构造函数 | 更新日期: 2023-09-27 18:33:11
我有两个接口,如ICustomerRepository,IBalanceRepository,由CustomerRepository实现.cs和BalanceRepository。现在对于条目,我有客户服务.cs构造器接受ICustomerRepository的实例。我正在调用一个从客户服务.cs到平衡服务的方法.cs该方法具有构造函数接受 IBalancerepository 的实例。我使用 Unity 注册了所有类并解决了客户服务,这是解析 ICustomerRespository,而不是 IBalanceRepository。我们可以像这样解析IBalanceRepository存储库吗?请参阅下面的代码并提出解决方案。
public interface ICusotmerRepository
{
void Add(string strCustomer);
}
public interface IBalanceRepository
{
void Add(decimal decAmount);
}
class CusotmerRepository : ICusotmerRepository
{
public void Add(string strCustomer)
{
Console.WriteLine("Added customer "+strCustomer);
}
}
class BalanceRepository : IBalanceRepository
{
public void Add(decimal decAmount)
{
Console.WriteLine("added amount "+decAmount);
}
}
public class BalanceService
{
private readonly IBalanceRepository _balanceRepository;
public BalanceService(IBalanceRepository balanceRepository)
{
_balanceRepository = balanceRepository;
}
public BalanceService()
{
}
public void AddBalance(decimal decBalance)
{
_balanceRepository.Add(decBalance);
}
}
class CustomerService
{
private readonly ICusotmerRepository _cusotmerRepository;
public CustomerService(ICusotmerRepository cusotmerRepository)
{
_cusotmerRepository = cusotmerRepository;
}
public void Process(string strCustomerName, decimal decBalance)
{
_cusotmerRepository.Add(strCustomerName);
var objBalanceService = new BalanceService();
objBalanceService.AddBalance(decBalance);
}
}
class Program
{
static void Main(string[] args)
{
var container = new UnityContainer();
container.RegisterType<IBalanceRepository, BalanceRepository>();
container.RegisterType<ICusotmerRepository, CusotmerRepository>();
var customerService = container.Resolve<CustomerService>();
customerService.Process("Ganesha",7);
}
}
问题就在这里:
public void Process(string strCustomerName, decimal decBalance)
{
_cusotmerRepository.Add(strCustomerName);
var objBalanceService = new BalanceService(); <------------
objBalanceService.AddBalance(decBalance);
}
您直接调用无参数构造函数 - Unity 无处将依赖项"注入"BalanceService
。
我看到三种可能性:
- 将构造函数参数添加到
CustomerService
以进行BalanceService
,并让 Unity 注入它 - 将构造函数参数添加到
CustomerService
IBalanceRepository
,并让 Unity 注入它,并在构造BalanceService
时传入它 - 将
IBalanceRepository
或BalanceService
作为参数添加到Process
您无法以这种方式解析 BalanceService,因为 Unity 无法知道何时需要解析此依赖关系。您可以通过构造函数参数将平衡服务注入客户服务。