locked
Open Closed Principle with Inheritance and Dependency Injection RRS feed

  • Question

  • User439975351 posted

    Sorry if this is a stupid question but I can't seem to find a definitive answer via the usual Googling/Stack Overflowing ;-)

    If I have an interface as follows:

    public interface IMyInterface
    {
        string Result(int number, Dictionary<int, string> interfaceParameters);
    }

    Then I inherit like so:

     public class TestClass : IMyInterface
     {
         public string Result(int number, Dictionary<int, string> interfaceParameters)
         {
             var sb = new StringBuilder();
    
             foreach (var m in interfaceParameters)
             {
                 sb.Append(m.Value);
             }
    
             var result = sb.ToString();
    
             return string.IsNullOrWhiteSpace(result) ? $"{number}" : result;
         }
    }

    Then I add this for DI (Asp Core): services.AddScoped<IMyInterface, TestClass>();

    Use it in the controller:

      [ApiController]
      [Route("[controller]")]
      public class TestController : ControllerBase
      {
         private readonly IMyInterface _testClass;
    
         public TestController(IMyInterface testClass)
         {
             _testClass = testClass;
         }
    
         [HttpGet]
         public IEnumerable<string> Get()
         {
             var interfaceParameters = new Dictionary<int, string>
             {
                 { 1, "One" },
                 { 2, "Two" }
             };
    
             var model = new List<string>();
    
             for (var i = 1; i <= 10; i++)
             {
                 model.Add(_testClass.Result(i, interfaceParameters));
             }
    
             return model;
         }
     }

    How would I extend the TestClass/IMyInterface using Open Close principles?

    Monday, January 27, 2020 7:34 PM

Answers

All replies