12

let's say this scenario:

public class B {};

public class C
{
     public C(B b){}
}

To resolve C from Autofac container, I have to register both B and C to container. But, today I used Unity, it seems I just need to register B to container, then C can be resolved.

So Autofac can't do as Unity do?

Benny
  • 8,547
  • 9
  • 60
  • 93

1 Answers1

21

With out-of-the-box Autofac it is expected that every type you want to use is registered with the container, either directly using the Register... methods or in bulk using RegisterAssemblyTypes. But there are other options too, take a look at Nicholas article about resolving everything. So yes, Autofac can do what Unity does, but you'll have to enable it.

Update: actually, the "resolve anything" feature is built-in now, and you can do the following:

        var cb = new ContainerBuilder();
        cb.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
        return cb.Build();

With the AnyConcreteTypeNotAlreadyRegisteredSource you can actually resolve both C and B without registering any of them.

Note that the lifetime of services resolved by AnyConcreteTypeNotAlreadyRegisteredSource will be "per dependency scope".

Note: this topic over at the Autofac discussion group is related.

Peter Lillevold
  • 33,668
  • 7
  • 97
  • 131
  • 1
    What's the default lifetime of the AnyConcreteTypeNotAlreadyRegisteredSource – JJS Jun 11 '14 at 16:43
  • 1
    @JJS - that would be the Autofac-in-general default lifetime, which is "per dependency scope" (ref https://code.google.com/p/autofac/wiki/InstanceScope) – Peter Lillevold Jun 12 '14 at 12:36