valdisiljuconoks / localization-provider-opti

Database driven localization provider for Optimizely (ex. Episerver) websites
Apache License 2.0
11 stars 17 forks source link

Using a ManualResourceProvider with constructor injection does not work in Optimizely CMS 12 #157

Closed andreas-valtech closed 2 years ago

andreas-valtech commented 2 years ago

Hi,

We are using DbLocalizationProvider.EPiServer v 7.2.0 in a CMS 12 site and localization works as it should. However we want to use a ManualResourceProvider but the EPiServer dependencies are not available with constructor injection if we place the code to add the provider in the ConfigureServices method in Startup:

public void ConfigureServices(IServiceCollection services)
{
   services.AddCms()

   services.AddDbLocalizationProvider(ctx =>
                ctx.ManualResourceProvider = new SomeManualResourceProvider());

}

We of cource place the call after AddCms() call but still does not work the dependencies are all null.

The SomeManualResourceProvider class uses ctor injection like this:

public class SomeManualResourceProvider : IManualResourceProvider
{
        private readonly ILanguageBranchRepository _languageBranchRepository;
        private readonly IContentTypeRepository _contentTypeRepository;

        public SomeManualResourceProvider() :
            this(ServiceLocator.Current.GetInstance<ILanguageBranchRepository>(),
             ServiceLocator.Current.GetInstance<IContentTypeRepository>())
        {
        }

        public SomeManualResourceProvider(
            ILanguageBranchRepository languageBranchRepository, 
            IContentTypeRepository contentTypeRepository)
        {
            _languageBranchRepository = languageBranchRepository;
            _contentTypeRepository = contentTypeRepository;
        }
}

I guess it would work if we put the call in an InitializableModule but have not not tried that yet. Still think IoC should work without using InitializableModule.

Maybe the call to add a ManualResourceProvider could move to Configure method and the UseDbLocalizationProvider method?

public void Configure(IApplicationBuilder app)
{
            app.UseDbLocalizationProvider(ctx => ctx.ManualResourceProvider = new SomeManualResourceProvider());
}
valdisiljuconoks commented 2 years ago

Hei,

Yes - seems like I didn't think through this. Will refactor to provide type instead. So when the resource provider will be created, I'll just ask IServiceProvider to give me an instance.

Thx for pointing this out! 👍