使用Autofac将依赖项注入控制台应用程序的Main入口点 [英] Using Autofac to inject a dependency into the Main entry point in a console app

查看:407
本文介绍了使用Autofac将依赖项注入控制台应用程序的Main入口点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个简单的控制台应用程序:

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!");
    }
}

使用Autofac注入Log实例并确保Log属性在运行时不会为null的最简单方法是什么?问题是我无法通过Main()传递它,而我正试图避免使用容器进行服务定位(正因为如此).

What is the simplest way I can use Autofac to inject the Log instance and ensure that the Log property will not be null at run time? The issue is that I can't pass it in through Main() and I'm trying to avoid service location using the container (just because).

推荐答案

您应该做的是将主逻辑中的所有逻辑提取到一个类中.此类可以具有带有依赖项的构造函数.您可以在主类中解决此类并调用它.然后,应将该类视为整个应用程序.现在,可以将Program类中发生的所有事情都视为您的组合根

What you should do is extract all logic from your main into a class. This class can have a constructor with dependencies. You resolve this class in the main and call it. This class should then be considered to be the entire application. Everything that happens inside the Program class can now be considered your Composition Root.

// 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()方法调用控制台应用程序是很不寻常的,如果存在,则应始终在组合根内部调用或连接它们.

Note that container.Resolve<ApplicationLogic>() doesn't just resolve the ApplicationLogic class, it resolves the entire object graph including all of ApplicationLogic's dependencies, and dependencies of those dependencies, etc. no matter how deep the graph is. The only thing you are responsible for is registering those dependencies in the ConfigureContainer() method. Therefore, it is somewhat unusual to have any more than 1 Resolve() method call a console application, and if there are, they should always be called or wired up inside of the composition root.

这篇关于使用Autofac将依赖项注入控制台应用程序的Main入口点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆