With Unity dependency can be resolved before the container is build. Is that possible with Autofac as well? Below code demonstrates my scenario - I'd need to resolve the ICacheRepository
in order to "new up" the singleton CacheHelper
.
In Unity that would be simply done with container.Resolve<ICacheRepository>()
in the place of ???. What about in Autofac?
var builder = new ContainerBuilder();
builder.RegisterType<CacheRepository>().As<ICacheRepository>();
var cacheHelper = new CacheHelper(???);
builder.RegisterInstance(cacheHelper).As<CacheHelper>();
Where CacheHelper
class has a constructor dependency on CacheRepository
.
public class CacheHelper
{
private readonly ICacheRepository _repository;
public CacheHelper(ICacheRepository repository)
{
_repository = repository;
}
}
You should not have to resolve component during build process. Autofac is able to solve object graph dependency. In your case CacheHelper
depends on ICacheRepository
so you just have to register CacheHelper
and ICacheRepository
var builder = new ContainerBuilder();
builder.RegisterType<CacheRepository>().As<ICacheRepository>();
builder.RegisterType<CacheHelper>().As<CacheHelper>();
When Autofac will resolve CacheHelper
it will create the dependency graph and create the instance of CacheHelper
with an instance ofsi ICacheRepository
. If you need to have a Singleton you can tell Autofac to create only a single instance.
var builder = new ContainerBuilder();
builder.RegisterType<CacheRepository>().As<ICacheRepository>();
builder.RegisterType<CacheHelper>().As<CacheHelper>().SingleInstance();
Another solution would be register lambda expression, these registrations are called when you need it, so you can resolve things during build process :
var builder = new ContainerBuilder();
builder.RegisterType<CacheRepository>().As<ICacheRepository>();
builder.Register(c => new CacheHelper(c.Resolve<ICacheRepository>()))
.As<CacheHelper>()
.SingleInstance(); // It will result of having one CacheHelper whereas
// ICacheRepository is declared as .InstancePerDependency
Be careful with this solution because ICacheRepository
is declared without scope the InstancePerDependency
scope will be used by default. Because CacheHelper
is SingleInstance
only a single instance of ICacheRepository
will be used which may result to bugs. See Captive Dependency for more information.
In your case, it doesn't seem like you need this kind of registration.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.