0

We use Autofac to do some simple dependency injection in our web app. It's all configured and registered in classes that operate behind-the-scenes. It makes injecting stuff in our project painless easy just like this:

//interface
public interface ISuperHereService
{ }

//class that uses the interface
public class SuperHeroFactory
{
    public ISuperHeroService SuperHeroService { get; }

    public SuperHeroFactory(ISuperHeroService superHeroService)
    {
       SuperHeroService = superHeroService;

       ...do all our stuff...

However now I had to create a separate project as a console app. My console app has a Main method.

I'm not at all sure how to inject an interface into the Main method.

Is this possible?

Thanks!

Scott Hannen
  • 27,588
  • 3
  • 45
  • 62
SkyeBoniwell
  • 6,345
  • 12
  • 81
  • 185
  • 2
    Take a look at [Autofac DI container in Console app](http://codereview.stackexchange.com/questions/56197/autofac-di-container-in-console-app) – Matias Cicero Aug 08 '16 at 20:28
  • 2
    explained here http://stackoverflow.com/questions/31903082/injection-into-console-application-with-the-simple-injector – Sol Stein Aug 08 '16 at 20:29

2 Answers2

6

Create and configure your container in Main (or in methods called from Main.) Then resolve an instance of SuperHeroFactory from the container and call whatever methods you need to.

Someone may object that you shouldn't resolve anything directly from the container. That's true, but Main is your composition root. It's where we're supposed to reference the container, so it's appropriate there.

Scott Hannen
  • 27,588
  • 3
  • 45
  • 62
  • I am doing this, but then my DI is not automatically available in a library that is referenced by the console app. ? – vicNeo May 04 '22 at 09:40
  • I don't understand exactly what you mean. (This was over 5 years ago.) It's probably good to ask as a new question. – Scott Hannen May 04 '22 at 13:44
3

No, don't do that in your Main() method; rather define a separate class which should take that ISuperHeroService instance and do necessary work. Then create an instance of that class in your Main() method and at the time instantiating you can perform the same DI likewise you are doing now.

Rahul
  • 76,197
  • 13
  • 71
  • 125