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?
When resolving a service, Autofac will automatically chain down the entire dependency hierarchy of the service and resolve any dependencies required to fully construct the service.
Register by Type var builder = new ContainerBuilder(); builder. RegisterType<ConsoleLogger>(); builder. RegisterType(typeof(ConfigReader)); When using reflection-based components, Autofac automatically uses the constructor for your class with the most parameters that are able to be obtained from the container.
From Visual Studio, you can get it via NuGet. The package name is Autofac. Alternatively, the NuGet package can be downloaded from the GitHub repository (https://github.com/autofac/Autofac/releases).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With