Solve Instance - Autofac

I am trying to figure out how to resolve an instance somewhere in the code.

When I started the application, I registered the type

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

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

StructureMAP has a static ObjectFactory.GetInstance<IFoo>() object

+6
autofac
source share
1 answer

Read Getting Started . He must start you.

First of all, you are looking for container . Create it from ContainerBuilder , as in this simple WinForms application:

 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 need to allow the first or topmost instance. The container will handle the creation of all other instances based on the input of dependencies through constructor parameters.

If the DI template is used throughout the application, you only need to touch the container once at startup.

How you decide the topmost instance depends a lot on what type of application you are building. If it is a web application, ASP.Net integration and MVC integration will take care of this for you. (In the end, the topmost instance in ASP.Net is the Application , which is not controlled by us).

On the other hand, if it is a console application or a WinForms application, you will manually enable the first instance in Main , as my example above.

+10
source share

All Articles