Exception accessing CurrentSite within HtmlFilter

Topics: Customizing Orchard
Dec 2, 2014 at 11:37 PM
I am getting an exception when I try to access the CurrentSite in the following code:
 public class HtmlFilterService : IHtmlFilter
        public HtmlFilterService(IOrchardServices services)
            var settings = services.WorkContext.CurrentSite.As<ImageResizerSettingsPart>();
The exception is:
Autofac.Core.DependencyResolutionException was unhandled by user code
  Message=An exception was thrown while invoking the constructor 'Void .ctor(Orchard.IOrchardServices)' on type 'HtmlFilterService'. ---> ValueFactory attempted to access the Value property of this instance. (See inner exception for details.)
       at Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate() in c:\Projects\OSS\autofac\Core\Source\Autofac\Core\Activators\Reflection\ConstructorParameterBinding.cs:line 137
       at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) in c:\Projects\OSS\autofac\Core\Source\Autofac\Core\Activators\Reflection\ReflectionActivator.cs:line 122
IHtmlFilter implements IDependency, so as far as I can tell there should be no problem getting access to OrchardServices, and indeed I DO get an OrchardServices object, which contains a valid WorkContext, but the WorkContext seems not to have access to the CurrentSite, and the exception above is thrown when I try to access it.

Can anyone enlighten me as to what's happening and what I need to do to access Settings from within an HtmlFilter?
Dec 3, 2014 at 12:51 AM
The issue maybe that you are accessing WorkContext and its CurrentSite property from the constructor - that may be too early.
Instead, try storing a reference to the injected "services" variable in a class level field, and then access that field when you need to (anywhere but the constructor).
Dec 3, 2014 at 1:27 AM
YES! That was it. I failed to realize that I couldn't simplify the code by eliminating the stored reference. Many thanks!