Autofac - resolve before build

与世无争的帅哥 提交于 2019-12-23 12:44:06

问题


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;
    }
} 

回答1:


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.



来源:https://stackoverflow.com/questions/34500858/autofac-resolve-before-build

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!