Вопрос

I have a spec translator, like below.

    //all specifications implement this base class
    public abstract class SpecBase
        {
            public abstract void Translate(IContext context);     
        }

 //spec translator implementation
        public interface ISpecTranslator
        {
            void Translate(IContext context);
        }

I need to inject the dependency of the SpecTranslator constructor. I have two ways to express the depenency.

Solution 1

 public class SpecTranslator:ISpecTranslator
    {
        IList<SpecBase> specs; 

      public SpecTranslator(IList<SpecBase> specs)
        {       
                this.specs = specs;
        }

    }

Please note using IList<SpecBase> works for now, but seems solution 2 provides more protection.

Solution 2:

 public class SpecTranslator:ISpecTranslator
    {
        ISpec spec;
      public SpecTranslator(ISpec spec)
        {       
                this.spec = spec;
        }

  }

    public interface ISpec
    {
        IList<SpecBase> specs {get;}
    }

However, the implementation of ISpec have the same problem when using constructor dependency injection.

Any idea on pros and cons on these two solutions, or other solutions?

Это было полезно?

Решение

It seems in order to "translate" (analyze) the list of specs, the contents of the ISpec instance given need to be destructured in all cases. A list has to be obtained and seen through. No matter how many layers of abstraction you weave in, the SpecTranslator will finally need a list.

In your case I'd think of ISpec as a factory. If the list is not lazily calculated there is no value in it.

Also, simplicity is an important design principle. As ISpec does not add any capability or architectural freedom it does not carry its own weight.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top