如何使用Unity.WebApi

时间:2018-11-14 18:16:20

标签: c# oop asp.net-web-api interface inversion-of-control

是否可以通过IOC在不同的类中公开类的公共属性。我正在创建接口的实例,但无法访问类的公共属性。我正在使用Unity.WebApi来解​​决依赖关系。

TransactionService类

public class TransactionService : ITransactionService
{
    private readonly IMRepository _mRepository;
    private readonly IFService _fGateway;

     public TransactionService(IMbaRepository mbaRepository, IFpnService fpnService)
    {
        _mRepository = mRepository;
        _fGateway = fService;
    }

     private List<Transaction> SearchTransacionsByUser(FUser objFUser)
    {

         foreach (var item in something)
         {
              //can't use _fGateway to set properties because Interface 
              //  don't implement them
              _fGateway.OID = objFUser.OID.ToString();
             _fGateway.Amount = objFUser.Amount;

             _fGateway.Search(criteria);

         }

    }



}

FService类

public class FService : IFpService
{

  public string _OID { get; set; }
  public decimal _Amount{ get; set; }

  public TransactionResponse Search(string criteria)
  {

         TransactionOperationInput _input;
            _input = new TransactionOperationInput()
            {
                Criteria = _criteria,
                OID = _OID,
                Amount = _Amount
            };

           // search transactions
     }



 }

1 个答案:

答案 0 :(得分:1)

如果您控制服务,则重构接口以公开所需的成员

public interface IFService {
   TransactionResponse Search(TransactionOperationInput input);
}

确保派生的实现具有这些成员

public class FService : IFpService {

    public TransactionResponse Search(TransactionOperationInput input) { 

           // search transactions
    }
}

并且依赖类使用正确的抽象

public class TransactionService : ITransactionService {
    private readonly IMRepository _mRepository;
    private readonly IFService fGateway;

    public TransactionService(IMbaRepository mbaRepository, IFService fService) {
        _mRepository = mRepository;
        fGateway = fService;
    }

    private List<Transaction> SearchTransacionsByUser(FUser objFUser) {    
        foreach (var item in something) {

            TransactionOperationInput input = new TransactionOperationInput() {
                Criteria = _criteria,
                OID =  objFUser.OID.ToString(),
                Amount = objFUser.Amount,
            };

             fGateway.Search(input);

            //...
         }

        //...
    }
}

最后确保在IoC / DI容器中注册适当的抽象和实现。