tags:

views:

100

answers:

1

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 structure mam there is a static object ObjectFactory.GetInstance<IFoo>()

+1  A: 

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.

Peter Lillevold
That's the example,but what If I need an instance in more classes? Can't register the type in every class.
But you have to somehow resolve this topmost instance somewhere in the code. The types get registered at the startup (Global.asax) and then you need to resolve the topmost instance somewhere in the code. Finally, I found an article decribing this. http://geekswithblogs.net/Sharpoverride/archive/2009/08/15/ioc-in-.net-part-1-autofac.aspxWhat do you think about this approach ?
See my updated answer... and yes, @Sharpoverrides approach is ok, it makes sure that Global.asax is not cluttered up with container-building code. After all, you really should write unittests that tests the container, and having a single-responsibility class that builds the container makes it easier to test.
Peter Lillevold
Thank you for your comprehensive explanation! It has really helped me!
Great, glad to be of assistance!
Peter Lillevold
I have one more question :-) How to resolve the first instance in a Windows Service which is hosting some WCF services ?
@user137348: check out the http://code.google.com/p/autofac/wiki/WcfIntegration. I've really not tried it out yet, but Windows services should be much like console apps when it comes to starting up.
Peter Lillevold