Unity解析嵌套构造函数

时间:2014-12-04 15:00:14

标签: c# unity-container

我有两个接口,如ICustomerRepository,IBalanceRepository,它们由CustomerRepository.cs和BalanceRepository实现。现在要进入,我有customerservice.cs,constuctor接受ICustomerRepository的实例。我正在调用一个方法,从customerservice.cs到BalanceService.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);
    }
}

2 个答案:

答案 0 :(得分:1)

您无法以这种方式解决BalanceService,因为Unity无法知道您何时需要解决此依赖关系。 您可以通过构造函数参数将BalanceService注入客户服务。

答案 1 :(得分:1)

问题在于:

public void Process(string strCustomerName, decimal decBalance)
{
    _cusotmerRepository.Add(strCustomerName);
    var objBalanceService = new BalanceService();    <------------
    objBalanceService.AddBalance(decBalance);
}

您正在直接调用无参数构造函数 - Unity无法注入&#34;注入&#34;依赖到BalanceService

我看到三种可能性:

  1. CustomerService的{​​{1}}添加构造函数参数,让Unity注入
  2. BalanceService的{​​{1}}添加一个构造函数参数,让Unity注入它,在构造CustomerService
  3. 时将其传入
  4. IBalanceRepositoryBalanceService作为参数添加到IBalanceRepository