解决实例 - Autofac实例、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...

我试图找出如何某处的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集成和的

阅读全文

相关推荐

最新文章