I have an interface and two classes
public interface IReportGenerator
{
void Process(ActivityReport activityReport);
}
class APReportGenerator : IReportGenerator
{
void Process(ActivityReport activityReport);
}
class ARReportGenerator : IReportGenerator
{
void Process(ActivityReport activityReport);
}
In my controller, based on user input, I am instantiating the child classes like this
public class AccountController : Controller
{
private IReportGenerator reportGenerator;
[HttpPost]
public IActionResult Submit(ActivityReport activityReport)
{
switch(activityReport.Type)
{
case "AR":
reportGenerator = new ARReportGenerator();
break;
case "AP":
reportGenerator = new APReportGenerator();
break;
}
reportGenerator.Process(activityReport);
...
}
}
Can someone please help me rewrite the code without the use of new?
In startup.cs, can I have something like this?
services.AddScoped<IReportGenerator, APReportGenerator>();
services.AddScoped<IReportGenerator, ARReportGenerator>();
And in controller?
public class AccountController : Controller
{
private readonly IReportGenerator reportGenerator;
public AccounterController(IReportGenerator reportGenerator)
{
this.reportGenerator = reportGenerator;
}
Sorry but I am stuck after this and dont know if this is correct or wrong.