Using Autofac to Insert a Dependency into the Main Entry Point in a Console Application

Say I have a simple console application:

public static class Program
{
    private static ILog Log { get; set; }

    public static void Main()
    {
        Log.Write("Hello, world!");
    }
}

In what simple way can I use Autofac to enter a log instance and make sure the Log property is not zero at runtime? The problem is that I cannot pass it through Main (), and I am trying to avoid the location of the service using the container (just because).

+6
source share
3 answers

, . . . . , Program, Root of Composition.

// Begin composition root
public static class Program
{
    public static void Main(string[] args) 
    {
        var container = ConfigureContainer();
        var application = container.Resolve<ApplicationLogic>();

        application.Run(args); // Pass runtime data to application here
    }

    private static IContainer ConfigureContainer()
    {
        var builder = new ContainerBuilder();

        builder.RegisterType<ApplicationLogic>.AsSelf();
        builder.RegisterType<Log>().As<ILog>();
        // Register all dependencies (and dependencies of those dependencies, etc)

        return builder.Build();
    }
}
// End composition root

public class ApplicationLogic
{
    private readonly ILog log;

    public ApplicationLogic(ILog log) {
        this.log = log;
    }

    public void Run(string[] args) {
        this.log.Write("Hello, world!");
    }
}

, container.Resolve<ApplicationLogic>() ApplicationLogic, , ApplicationLogic, .., , . , , - ConfigureContainer(). 1 Resolve(), , , .

+11

-. Main() .

+2

I had to change builder.RegisterType.AsSelf (); at builder.RegisterType (). AsSelf (); so that it works for me

0
source

Source: https://habr.com/ru/post/1526637/


All Articles