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?
Create a new class that implements the interface but has a different implementation. IMHO, it seems your design is very specific and not open to a different implementation
public class NewTestClass : IMyInterface
{
public string Result(int number, Dictionary<int, string> interfaceParameters)
{
//New implementation code
}
}
Member
31 Points
147 Posts
Open Closed Principle with Inheritance and Dependency Injection
Jan 27, 2020 07:34 PM|1jus|LINK
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:
Then I inherit like so:
Then I add this for DI (Asp Core): services.AddScoped<IMyInterface, TestClass>();
Use it in the controller:
How would I extend the TestClass/IMyInterface using Open Close principles?
All-Star
53101 Points
23659 Posts
Re: Open Closed Principle with Inheritance and Dependency Injection
Jan 27, 2020 08:37 PM|mgebhard|LINK
Create a new class that implements the interface but has a different implementation. IMHO, it seems your design is very specific and not open to a different implementation
http://joelabrahamsson.com/a-simple-example-of-the-openclosed-principle/
Member
31 Points
147 Posts
Re: Open Closed Principle with Inheritance and Dependency Injection
Jan 27, 2020 08:49 PM|1jus|LINK
How could I use this with DI if I already have it added here?:
services.AddScoped<IMyInterface, TestClass>();
All-Star
53101 Points
23659 Posts
Re: Open Closed Principle with Inheritance and Dependency Injection
Jan 27, 2020 09:04 PM|mgebhard|LINK
Use a factory pattern if you have multiple implementations of the same interface.
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1
https://espressocoder.com/2018/10/08/injecting-a-factory-service-in-asp-net-core/
Member
31 Points
147 Posts
Re: Open Closed Principle with Inheritance and Dependency Injection
Jan 27, 2020 09:56 PM|1jus|LINK
Kind regards,
Justin