Axel Andersen
Axel Andersen

Reputation: 350

.Net Core Dependency Injection in Console App

I am trying to use dependency injection in a .NET Core Console App. There are a lot of articles about it, but did not find one that fixes my problem. I am trying to use services original from an aspnet core web app, thats why i have the WebHost.

My main problem is to create an instance of my own class, all the dependency seems to work, and my console app starts up.

I have this code in my Program class:

static void Main(string[] args)
{            
    var host = WebHost.CreateDefaultBuilder(args)
        .UseKestrel(options => options.AddServerHeader = false)
        .UseStartup<Startup>()
        .Build();

    var services = new ServiceCollection().AddLogging();            
    var container = new Container();           
    var serviceProvider = container.GetInstance<IServiceProvider>();

This code will not compile due to this error: 'Container' does not contain a definition for 'GetInstance'

How can i create an instance of my custom class App which has this implementation:

public class App
{
    private readonly IProductService _productService;

    public App(IProductService productService)
    {
        _productService = productService;
    }
}

Upvotes: 1

Views: 4062

Answers (2)

Kirk Larkin
Kirk Larkin

Reputation: 93303

You don't even need to create your own ServiceCollection or ServiceProvider in this scenario - You can just use the IWebHost's Services property that you already have:

var app = host.Services.GetService<App>();

WebHost.CreateDefaultBuilder already adds the logging services, so there's no need to do that either.

Note: I'm assuming that you've registered your App and IProductService types in Startup.ConfigureServices.

Upvotes: 1

nvoigt
nvoigt

Reputation: 77364

I have no idea what a "Container" is in your setting, but you normally create a service provider by calling BuildServiceProvider on the ServiceCollection.

var provider = services.BuildServiceProvider();

var instance = provider.GetService<App>();

You will need to register both App and whatever IProductService you want with the services collection first though.

Upvotes: 1

Related Questions