0

I am getting below error in the logs, when I am overriding Sitecore Dependency Injection with Autofac DI. I am using Sitecore 9.2.

The main issue is with Create Actions on EXM & Forms.

Can anyone help regarding this?

15832 19:55:56 DEBUG Autofac.Core.DependencyResolutionException: An exception was thrown while activating λ:System.Web.HttpContextBase. ---> Autofac.Core.DependencyResolutionException: A delegate registered to create instances of 'System.Web.HttpContextBase' returned null.
   at Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters, Object& decoratorTarget)
   --- End of inner exception stack trace ---
   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters, Object& decoratorTarget)
   at Autofac.Core.Resolving.InstanceLookup.Execute()
   at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters)
   at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters)
   at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance)
   at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable`1 parameters)
   at Autofac.Extensions.DependencyInjection.AutofacServiceProvider.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
   at Sitecore.DependencyInjection.SitecorePerRequestScopeModule.TryGetScope(IServiceProvider serviceProvider)

Adding BuildServiceProvider Code below.

protected override IServiceProvider BuildServiceProvider(IServiceCollection serviceCollection)
{
    var mapper = BuildMapper();
    var config = new Ioc.Config().Map(mapper);

    var builder = new ContainerBuilder();

    serviceCollection.AddAutofac();

    builder.Populate(serviceCollection);

    var executingAssembly = Assembly.GetExecutingAssembly();

    builder.Register(c => mapper).As<IMapper>().SingleInstance();

    builder.RegisterType<MvcContext>().As<IMvcContext>().AsSelf().InstancePerRequest();
    builder.RegisterType<Glass.Mapper.Sc.Web.RequestContext> ().As<Glass.Mapper.Sc.Web.IRequestContext>().AsSelf().InstancePerRequest();
    builder.RegisterType<Glass.Mapper.Sc.Web.WebForms.WebFormsContext > ().As<Glass.Mapper.Sc.Web.WebForms.IWebFormsContext>().AsSelf().InstancePerRequest();            
    builder.RegisterType<GlassHtml>().As<IGlassHtml>().AsSelf().InstancePerRequest();
    builder.RegisterType<SitecoreService>().As<ISitecoreService>().AsSelf().InstancePerRequest();


    builder.RegisterAssemblyTypes(typeof(SyncTask).Assembly).AssignableTo<SyncTask>().AsSelf().InstancePerRequest();
    //builder.RegisterAssemblyTypes(executingAssembly).AsSelf().SingleInstance();

    builder.RegisterType<JobsService>().AsSelf().InstancePerRequest();
    builder.RegisterType<JobAlertService>().AsSelf().InstancePerRequest();
    builder.RegisterType<NavigationService>().AsSelf().InstancePerRequest();
    builder.RegisterType<RecaptchaService>().AsSelf().InstancePerRequest();
    builder.RegisterType<CandidateService>().As<ICandidateService>().InstancePerRequest();
    builder.RegisterType<CandidateJobService>().AsSelf().InstancePerRequest();
    builder.RegisterType<MyAccountService>().As<IMyAccountService>().InstancePerRequest();
    builder.RegisterType<PasswordStorage>().As<IPasswordHasher>().InstancePerRequest();
    builder.RegisterType<PageMetaMediator>().AsSelf().SingleInstance();

    builder.Register(c =>
        {
            var scope = c.Resolve<ILifetimeScope>();
            var globalConfig = scope.Resolve<GlobalConfig>();
            return new CachedLocationService(globalConfig, new LocationService(globalConfig));
        })
        .As<ILocationService>()
        .SingleInstance();

    builder.Register(c =>
        {
            var scope = c.Resolve<ILifetimeScope>();
            var globalConfig = scope.Resolve<GlobalConfig>();
            var currencySanatiser = scope.Resolve<ICurrencySanatiser>();
            return new CachedCurrencyService(globalConfig, currencySanatiser, new CurrencyService(globalConfig, currencySanatiser));
        })
        .AsImplementedInterfaces()
        .SingleInstance();

    builder.Register(c =>
        {
            var scope = c.Resolve<ILifetimeScope>();
            var globalConfig = scope.Resolve<GlobalConfig>();
            return new CachedSharePriceFeedService(globalConfig, new SharePriceFeedService());
        })
        .AsImplementedInterfaces()
        .SingleInstance();

    builder.Register(c =>
    {
        var scope = c.Resolve<ILifetimeScope>();
        var globalConfig = scope.Resolve<GlobalConfig>();
        if (globalConfig.GdprDataApi == null || String.IsNullOrEmpty(globalConfig.GdprDataApi.ClientId) || String.IsNullOrEmpty(globalConfig.GdprDataApi.ClientSecret))
            return null;

        return new GdprDataService(globalConfig);
    })
    .AsSelf()
    .SingleInstance();

    builder.RegisterType<BreadcrumbService>().As<IBreadcrumbService>().InstancePerRequest();
    builder.RegisterType<ContentSearchService>().AsSelf().InstancePerRequest();
    builder.RegisterType<EventSearchService>().AsSelf().InstancePerRequest();
    builder.RegisterType<JobResultsBuilder>().AsSelf().InstancePerRequest();
    builder.RegisterType<JobApplicationsBuilder>().AsSelf().InstancePerRequest();
    builder.RegisterType<JobFilterBuilder>().AsSelf().InstancePerRequest();
    builder.RegisterType<CryptoService>().AsSelf().InstancePerRequest();
    builder.RegisterType<CompressorService>().AsSelf().InstancePerRequest();
    builder.RegisterType<ArticleSearchQueryBuilder>().As<IArticleSearchQueryBuilder>().InstancePerDependency();
    builder.RegisterType<JobSearchQueryBuilder>().As<IJobSearchQueryBuilder>().InstancePerDependency();
    builder.RegisterType<ArticleSearchDefaultsBuilder>().As<IArticleSearchDefaultsBuilder>().InstancePerDependency();
    builder.RegisterType<ArticleSearcher>().As<IArticleSearcher>().InstancePerDependency();

    builder.RegisterType<SavedJobBuilder>().AsSelf().InstancePerRequest();
    builder.RegisterType<SavedSearchBuilder>().AsSelf().InstancePerRequest();
    builder.RegisterType<BasicQueryBuilder>().As<IBasicQueryBuilder>().InstancePerDependency();
    builder.RegisterType<CloudDocumentService>().As<ICloudDocumentService>().InstancePerRequest();
    //builder.RegisterType<SharePriceFeedService>().As<ISharePriceFeedService>().InstancePerRequest();
    builder.RegisterType<RedisCacheManager>().As<IRedisCacheManager>().InstancePerDependency();
    builder.RegisterType<GdprDataService>().As<IGdprDataService>().InstancePerRequest();

    builder.Register(c =>
        {
            var scope = c.Resolve<ILifetimeScope>();
            var globalConfig = scope.Resolve<GlobalConfig>();

            return new GoogleJobsServiceHelper(globalConfig);
        })
        .AsSelf()
        .SingleInstance();

    builder.RegisterType<GoogleJobsService>().As<IExternalJobSearchIndexService>().InstancePerRequest();

    // Feed Builders
    builder.RegisterType<IndeedFeedWriter>().As<IFeedWriter>().Named<IFeedWriter>("indeed");
    builder.RegisterType<IndeedFeedBuilder>().As<IIndeedFeedBuilder>().InstancePerRequest();
    builder.RegisterType<IndeedFeedModelSerializor>().As<IIndeedFeedModelSerializor>().InstancePerRequest();

    builder.RegisterType<ClickwiseFeedWriter>().As<IFeedWriter>().Named<IFeedWriter>("clickwise");
    builder.RegisterType<ClickwiseFeedBuilder>().As<IClickwiseFeedBuilder>().InstancePerRequest();
    builder.RegisterType<ClickwiseFeedModelSerializor>().As<IClickwiseFeedModelSerializor>().InstancePerRequest();

    builder.RegisterType<ZipRecruiterFeedWriter>().As<IFeedWriter>().Named<IFeedWriter>("ziprecruiter");
    builder.RegisterType<ZipRecruiterFeedBuilder>().As<IZipRecruiterFeedBuilder>().InstancePerRequest();
    builder.RegisterType<ZipRecruiterFeedModelSerializor>().As<IZipRecruiterFeedModelSerializor>().InstancePerRequest();

    builder.RegisterType<JobRapidoFeedWriter>().As<IFeedWriter>().Named<IFeedWriter>("jobrapido");
    builder.RegisterType<JobRapidoFeedBuilder>().As<IJobRapidoFeedBuilder>().InstancePerRequest();
    builder.RegisterType<JobRapidoFeedModelSerializor>().As<IJobRapidoFeedModelSerializor>().InstancePerRequest();

    builder.RegisterType<TalentNexusFeedWriter>().As<IFeedWriter>().Named<IFeedWriter>("talentnexus");
    builder.RegisterType<TalentNexusFeedBuilder>().As<ITalentNexusFeedBuilder>().InstancePerRequest();
    builder.RegisterType<TalentNexusFeedModelSerializor>().As<ITalentNexusFeedModelSerializor>().InstancePerRequest();

    builder.RegisterType<ForcesNetRecruiterFeedWriter>().As<IFeedWriter>().Named<IFeedWriter>("forcesnet");
    builder.RegisterType<ForcesNetRecruiterFeedBuilder>().As<IForcesNetRecruiterFeedBuilder>().InstancePerRequest();
    builder.RegisterType<ForcesNetRecruiterFeedModelSerializor>().As<IForcesNetRecruiterFeedModelSerializor>().InstancePerRequest();

    builder.Register<FeedBuilderFactory>((context, parameters) =>
        {
            var scope = context.Resolve<ILifetimeScope>();
            return type =>
            {
                var builderType = type.ToLower().Trim();
                return scope.ResolveOptionalNamed<IFeedWriter>(builderType);
            };
        }).AsSelf().InstancePerDependency();
    builder.Register<SyncTask.SyncTaskFactory>(c =>
        {
            var scope = c.Resolve<ILifetimeScope>();
            return (t => scope.Resolve(t) as SyncTask);
        }).AsSelf().InstancePerRequest();
    builder.Register(c => config).AsSelf().SingleInstance();

    builder.RegisterType<JobSearchFilterCoodinateLookup>().As<IJobSearchFilterCoordinateLookup>().InstancePerRequest();
    builder.RegisterType<SalaryNormaliser>().As<ISalaryNormaliser>().InstancePerRequest();
    builder.RegisterType<JobsSearchResultVmBuilder>().As<IJobsSearchResultVmBuilder>().InstancePerRequest();
    builder.RegisterType<TimeRemainingVmBuilder>().As<ITimeRemainingVmBuilder>().InstancePerRequest();
    builder.RegisterType<SalaryDescriptionBuilder>().As<ISalaryDescriptionBuilder>().InstancePerRequest();
    builder.RegisterType<CurrencySanatiser>().As<ICurrencySanatiser>().SingleInstance();
    builder.RegisterType<JobSearcher>().As<IJobSearcher>().InstancePerRequest();

    //builder.Register(c => new HttpContextWrapper(HttpContext.Current)).As<HttpContextBase>().InstancePerRequest();

    builder.RegisterModule<MediatRModule>();
    //builder.RegisterModule(new AutofacWebTypesModule());

    builder.RegisterControllers(executingAssembly);
    builder.RegisterApiControllers(executingAssembly);

    builder.RegisterModelBinders(typeof(JobFilterModelBinder).Assembly);
    builder.RegisterModelBinderProvider();
    builder.RegisterFilterProvider();

    //builder.RegisterAssemblyModules(executingAssembly);

    var container = builder.Build();

    var mvcResolver = new AutofacDependencyResolver(container);
    var webApiResolver = new AutofacWebApiDependencyResolver(container);                                 


    // Register the resolver as the ASP.net WebApi2 resolver.
    //GlobalConfiguration.Configuration.DependencyResolver = new ConditionalDependencyResolver(webApiResolver, GlobalConfiguration.Configuration.DependencyResolver);

    GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

    // Register the resolver as the ASP.net MVC resolver.

    DependencyResolver.SetResolver(mvcResolver);

    AutofacDependencyResolver.SetAutofacDependencyResolverAccessor(() => mvcResolver);

    // Register the resolver with Sitecore controller factory.
    //ControllerBuilder.Current.SetControllerFactory(new AutofacControllerFactory(mvcResolver, ControllerBuilder.Current.GetControllerFactory()));

    RouteTable.Routes.MapRoute("Service", @"service/{action}", new { controller = "Service" });
    RouteTable.Routes.MapRoute("Indeed", @"feed/{builderType}/{jobRepositoryId}", new { controller = "Feed", action = "Build", jobRepositoryId = UrlParameter.Optional });
    RouteTable.Routes.MapRoute("SitecoreShellDefault", @"sitecore/shell/mvc/{controller}/{action}", new { controller = "CustomEditor" });

    AntiForgeryConfig.SuppressIdentityHeuristicChecks = true;

    //Translate.ResetCache(true);

    // Custom model binders
    //HttpContext.Current.Items["77D90B5A-236C-4116-8C4E-E4517753E74C"] = new VersionCountDisabler();

    RegisterSocialDependencies();          

    return container.Resolve<IServiceProvider>();
}
8
  • I guess the issue is because Sitecore EXM or forms are based on Sitecore MVC controllers and AutoFac is not able to resolve them, Please share the code on how you are registering Autofac
    – Abhay Dhar
    Commented Jan 29, 2020 at 8:42
  • Hi Abhay, I am extending the Default ServiceProvider and overriding it with Autofac. Then I patched the Service Provider using configuration patch file. Can you let me know how you can register the Sitecore MVC Controllers in Autofac? Commented Jan 29, 2020 at 11:07
  • I have updated the BuildServiceProvider Method Code as well. Commented Jan 29, 2020 at 11:12
  • Yes , your implementation looks correct , but you may also need a chainedmvcresolver sitecorecorner.com/2016/01/20/…
    – Abhay Dhar
    Commented Jan 29, 2020 at 12:40
  • medium.com/@structuredcode/… Which Sitecoreversion are you using ?
    – Abhay Dhar
    Commented Jan 29, 2020 at 12:41

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.