Alejandro Mora
Alejandro Mora

Reputation: 177

How can i should handle the injection of service domain?

I'm building a financial application where i have two ways to calculate the balance of the credit so i try to follow a design based on Domain Driven Design and i feel some confused respect how supose that i have to inject the balance calculator in the credit entity. i try to insert a interface in credit called IBalanceCalculator then when i call method CalculateBalanceAtDate in the credit this determine what instance use

this is the example

credit {
  protected  IBalanceCalcultar _calculator;
  ....
    private void _InitializeBalanceCalculator()
    {
        if (_balanceCalculator == null)
            switch (InterestType)
            {
                case EInterestType.OutstandingBalance:
                    _balanceCalculator = new OutstandingBalanceService();
                    break;
                case EInterestType.GlobalBalance:
                    _balanceCalculator = new GlobalBalance();
                    break;
                default:
                    throw new Exception();
            }
    }
    public void CalculateBalanceAtDate(DateTime date, bool moratory)
    {
        _InitializeBalanceCalculator();
        _balanceCalculator.GetBalance(this, date);
    }
}

but i feel that this way is not so good

someone can clarify me is correct or if exists a better way

Upvotes: 0

Views: 57

Answers (2)

Sylvain Lecoy
Sylvain Lecoy

Reputation: 1017

Why you need to inject the service ?

Just pass it as a parameter of your method.

You then wire the whole in your application service at the application level !

Domain Services as a parameter are perfectly fine, it makes your domain object testable as well.

Upvotes: 0

VoiceOfUnreason
VoiceOfUnreason

Reputation: 57239

someone can clarify me is correct or if exists a better way

Sounds like your domain has a concept like an InterestPolicy that determines what strategy should be used to calculate the balance. Find out what the name of that thing is in your domain (your domain experts will know), and pass it in as an argument

public Balance CalculateBalanceAtDate(
    InterestPolicy interestPolicy, 
    DateTime date, 
    bool moratory)
{
    IBalanceCalculator calculator interestPolicy.balanceCalculator(this.interestType)
    return calculator.balance(this, date)
}

Slightly better is to take the entity itself out of the equation, and just pass state

public Balance CalculateBalanceAtDate(
    InterestPolicy interestPolicy, 
    DateTime date, 
    bool moratory)
{
    IBalanceCalculator calculator interestPolicy.balanceCalculator(this.interestType)
    return calculator.balance(this.creditHistory, date)
}

Upvotes: 2

Related Questions