how to use constructor in c# main program.cs to inject an interface

Viewed 2143

I'm new in programming, I have created an interface which name is IPointCalculator I have implemented it in this class:

public class PointCalculator : IPointCalculator
{
    EnemisEntity enm = new EnemisEntity();
    public int pointCal(string enemyType)
    {
        int point = 0;

        if (enemyType == enm.banzai_Bill)
        {
            point = 200;

        }
        else if (enemyType == enm.beach_koopa)
        {
            point = 400;

        }
        else if (enemyType == enm.big_boo)
        {

            point = 800;
        }

        else if(enemyType==enm.blargg)
        {
            point = 1600;
        }

        return point;

    }
}

now in my console application, I want to use it:

class Program
{
    IPointCalculator _ipCal;
    Program(IPointCalculator pntCal)
    {

        _ipCal = pntCal;
    }
    public  static void Main(string[] args)
    {

        
    }
}

but I cant use _ipCal in my Main, how should I use it here? Is it the right way?

2 Answers

The goal is to untie / loosely couple the entry point (the actual console application) from what you want it to do (PointCalculator).

Create a wrapper class (MyProgram) so you can inject the implementation. From there, you can look at more advanced options like using a dependency injection tool.

class Program
{    
   public static void Main(string[] args)
   {  
      var instance = new PointCalculator();
      var program = new MyProgram(instance);
   }
}

public class MyProgram
{
   private readonly IPointCalculator _pointCalcuator;

   public MyProgram(IPointCalculator pntCal)
   {
      _pointCalculator = pntCal;
   }
}

You can't use the interface in the Main method because the method is static. The console app also doesn't know by default that PointCalculator is the implementation of IPointCalculator.

You can use Dependency Injection for this, which is a very common pattern.

It allows you to do the following:

using Microsoft.Extensions.DependencyInjection;

class Program
{
   static void Main(string[] args)
   {
       IServiceCollection services = new ServiceCollection();

       Startup startup = new Startup();
       startup.ConfigureServices(services);

       IServiceProvider serviceProvider = services.BuildServiceProvider();

       // entry to run app
       serviceProvider.GetService<Runner>().Run();
    }
}
public class Startup
{
   public void ConfigureServices(IServiceCollection services)
   {
       services.AddTransient<IPointCalculator, PointCalculator>();
       services.AddTransient<Runner>();
   }
}
public class Runner
{
    private readonly IPointCalculator _pointCalculator;

    public Runner(IPointCalculator pointCalculator)
    {
        _pointCalculator = pointCalculator;
    }

    public void Run()
    {
        // I can use the point calculator!
    }
}
Related