解析实例 - Autofac [英] Resolve instance - Autofac

查看:22
本文介绍了解析实例 - Autofac的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试弄清楚如何解析代码中某处的实例.

I'm trying to figure out how to resolve a instance somewhere in the code.

在应用程序启动时我注册了一个类型

At the application startup I registered a type

static void Main()
{    
    var builder = new ContainerBuilder();
    builder.RegisterType<Foo>().As<IFoo>();
}

现在,我该如何解析代码中某处的实例?

Now, how can I resolve an instance somewhere in the code ?

在 StructureMAP 中有一个静态对象 ObjectFactory.GetInstance()

In StructureMAP there is a static object ObjectFactory.GetInstance<IFoo>()

推荐答案

阅读 Getting开始.它应该可以帮助您入门.

Read up on Getting Started. It should get you started.

首先,您要查找的是容器.像在这个简单的 WinForms 应用程序中一样,从 ContainerBuilder 构建它:

First off, what you are looking for is the container. Build it from the ContainerBuilder like in this simple WinForms app:

static void Main()
{
    using (var container = builder.Build())
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        var mainForm = container.Resolve<MainForm>();
        Application.Run(mainForm)
    }
}

一般的想法是您只需要解析第一个或最顶层的实例.容器将通过构造函数参数处理基于依赖注入的所有其他实例的创建.

The general idea is that you only have to resolve the first or topmost instance. The container will handle creating all other instances based on dependency injection through constructor parameters.

如果整个应用程序都遵循 DI 模式,则您只需在启动时接触容器一次.

If the DI pattern is followed throughout your application you should only have to touch the container once at startup.

您如何解析最顶层实例很大程度上取决于您正在构建的应用程序类型.如果是网络应用程序,ASP.Net 集成MVC 集成 将为您处理.(毕竟,ASP.Net 中最顶层的实例是我们无法控制的 Application).

How you resolve the topmost instance depends largely on what type of application you are building. If its a web app, the ASP.Net integration and MVC integration will take care of it for you. (After all, the topmost instance in ASP.Net is the Application which is out of our control).

另一方面,如果它是控制台应用程序或 WinForms 应用程序,您将在 Main 中手动解析第一个实例,就像我上面的示例一样.

On the other hand, if its a console app or WinForms app you would resolve the first instance manually in Main, like my sample above.

这篇关于解析实例 - Autofac的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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