I have come into an already-written app that uses Dependency Injection and I've successfully added to one of the existing projects in the solution, now trying to add a NEW project and can't really seem to get things figured out.
Because it's a CONSOLE app and not an MVC app, I'm really thrown with how to setup the Program.cs
to work.
Basically, I need to know how to use the ProjectSearchManager
(via IProjectSearchManager
) from a console app.
These are the relevant (I think) sections of my Startup.cs
...
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DataConnection")));
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
ConfigureRepositories(services);
ConfigureManagers(services);
}
private static void ConfigureRepositories(IServiceCollection services)
{
services.AddScoped<IAdoRepository, AdoRepository>();
services.AddScoped<IRepository<ProjectSearchResults>, Repository<ProjectSearchResults>>();
}
private static void ConfigureManagers(IServiceCollection service)
{
service.AddScoped<IProjectSearchManager, ProjectSearchManager>();
}
}
What is the syntax that works to do something similar in Program.cs
?
Currently I have this...
public class Program
{
public static void Main(string[] args)
{
var services = new ServiceCollection();
ConfigureRepositories(services);
ConfigureManagers(services);
// NOW I WANT TO RUN METHODS INSIDE ProjectSearchManager...
// HOW?
}
public static void ConfigureRepositories(IServiceCollection services)
{
services.AddScoped<IAdoRepository, AdoRepository>();
services.AddScoped<IRepository<ProjectSearchManager>, Repository<ProjectSearchManager>>();
}
public static void ConfigureManagers(IServiceCollection service)
{
service.AddScoped<IProjectSearchManager, ProjectSearchManager>();
}
}
And the code seems to run but I can't access the methods inside ProjectSearchManager
... I can't figure out what I'm missing or where I'm going wrong.
This may be very basic dependency injection stuff, I don't know. I was able to get it to work in MVC easily but in the console app, seems like the setup is more challenging or something.
Any help greatly appreciated, thanks!
UPDATE...
I reviewed the post at --> How to run .NET Core Console app using generic host builder
I tried updating the code to read as such...
var host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services => { services.AddScoped<ProjectSearchManager>(); })
.Build();
var my = host.Services.GetRequiredService<ProjectSearchManager>();
my.SearchAsync();
I get the following error... Unable to resolve service for type 'Solution.DataLayer.Abstracts.IRepository`1[Solution.DataLayer.Entities.ProjectSearchResults]' while attempting to activate 'Solution.Managers.ProjectSearchManager'.