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

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

问题描述

我试图找出如何某处的code解析一个实例。

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>();
}

现在,我怎么能在某处的code解决一个实例?

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

在StructureMAP有一个静态对象 ObjectFactory.GetInstance&LT;的IFoo&GT;()

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

推荐答案

阅读上入门。它应该让你开始。

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

首先,你在找什么是容器。从构建它的 ContainerBuilder 想在这个简单的WinForms应用程序:

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.

您如何解决最顶层的实例,在很大程度上取决于你正在构建的应用程序类型。如果它是一个Web应用程序中, ASP.Net集成和的MVC整合会照顾它。 (毕竟,在ASP.Net最上面的实例是应用程序这是在我们控制的)。

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应用程序,你会手动主要解决的第一个实例,像我样的上方。

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天全站免登陆