I am using DI in my dot net console application. I have an interface:
public interface IMainAction
{
void Run();
}
and 2 classes implementing this Interface.
I have configured my DI host like this:
static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureServices((context, services) =>
{
services.AddTransient<IMainAction, CityStoreClass>();
services.AddTransient<IMainAction, ProvinceService>();
services.AddSingleton<App>();
}).UseSerilog();
}
My app class :
public class App
{
private IMainAction _cityService;
private IMainAction _ProvinceService;
private readonly ILogger<CityStoreClass> _log;
private readonly IConfiguration _config;
public App(IMainAction cityService, IMainAction provinceService, ILogger<CityStoreClass> log, IConfiguration config)
{
_cityService = cityService;
_ProvinceService = provinceService;
_log = log;
_config = config;
}
public void Run(string[] args)
{
Log.Logger.Information("App Run Starts");
var connectionString = _config.GetValue<string>("ConnectionString");
_log.LogInformation($"{connectionString}");
((CityStoreClass)_cityService).Run();
}
}
I want to call Run
method of _cityService
class, but I got this error:
Unable to cast object of type 'EazyCityCA.Services.ProvinceService' to type 'EazyCityCA.Services.CityStoreClass'.
What is the problem?