Home > Mobile >  Dependency injection have two instances of same dependency
Dependency injection have two instances of same dependency

Time:04-18

I've been struggling with a small DI problem, that I think should be very easy to solve, but for some reason I can't find the solution.

I have a service that should one one DI object in the same way for two different things.

public class EquationManager : IEquationManager
{
       private readonly IEquationEvaluator _equationEvaluator;
       private readonly IEquationEvaluator _inversEquationEvaluator;
    
       public EquationManager(IEquationEvaluator equationEvaluator)
       {
           _equationEvaluator = equationEvaluator;
           _inversEquationEvaluator = equationEvaluator;
       }
}

So what I would need is 2 instances of the same DI. That's all. If I write the code as it is, they are shallow copies, what ever I set to _inversEquationEvaluator is also updated in _equationEvaluator ( which is normal).

How do I have 2 separate instances of the same DI? Is this possible in a simple way. I would like to avoid registering IEquationEvaluator in 2 different ways in the container.

My second question: is my architecture wrong? What I want to achieve here is having an math equation that takes an input parameter (int) and output a double value. I need now a way to revert this process using an other equation. So I input a double value and in theory I should obtain an int value. IEquationEvaluator is a class that deals with the math operation.

CodePudding user response:

You can use this pattern:

 public enum EquationEvaluatorType
    {
        EquationEvaluator,
        InversEquationEvaluator
    }


    public interface IEquationEvaluator
    {
        public EquationEvaluatorType Type { get; }

        //your methods and properties
    }

    public class EquationEvaluator : IEquationEvaluator
    {
        public EquationEvaluatorType Type => EquationEvaluatorType.EquationEvaluator;
    }

    public class InversEquationEvaluator : IEquationEvaluator
    {
        public EquationEvaluatorType Type => EquationEvaluatorType.InversEquationEvaluator;
    }

    public class EquationManager : IEquationManager
    {
        private readonly IEquationEvaluator _equationEvaluator;
        private readonly IEquationEvaluator _inversEquationEvaluator;

        public EquationManager(IEnumerable<IEquationEvaluator> items)
        {
            _equationEvaluator = items.First(x=>x.Type==EquationEvaluatorType.EquationEvaluator);
            _inversEquationEvaluator = items.First(x => x.Type == EquationEvaluatorType.InversEquationEvaluator);
        }
    }

And in your startup:

  services.AddScoped<IEquationEvaluator, EquationEvaluator>();
  services.AddScoped<IEquationEvaluator, InversEquationEvaluator>();
  • Related