Resolve instance - Autofac

北城以北 提交于 2019-12-18 04:14:37

问题


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 ?

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


回答1:


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

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.

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

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).

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.



来源:https://stackoverflow.com/questions/2737139/resolve-instance-autofac

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!