Five New Optimizely Certifications are Here! Validate your expertise and advance your career with our latest certification exams. Click here to find out more

How to get IContentLoader using constructor injection

Vote:
0

I have this code

var loader = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance();

I want to get the instance of IContentLoader using constructor injection.

How i can do that.

#198425
Edited, Oct 29, 2018 5:36
Vote:
0

You should be using something like this

public class MyClass

{

privat IContentLoader _contentLoader;

public MyClass(IContentLoader contentLoader)

{

_contentLoader = contentLoader;

}

}

#198430
Oct 29, 2018 7:48
Vote:
1

Hi Janmejay,

You have to set Dependency Resolver in ASP.NET.

This is a code sample from Alloy:

[InitializableModule]
    public class DependencyResolverInitialization : IConfigurableModule
    {
        public void ConfigureContainer(ServiceConfigurationContext context)
        {
        }

        public void Initialize(InitializationEngine context)
        {
            DependencyResolver.SetResolver(new ServiceLocatorDependencyResolver(context.Locate.Advanced));
        }

        public void Uninitialize(InitializationEngine context)
        {
        }

        public void Preload(string[] parameters)
        {
        }
    }

    public class ServiceLocatorDependencyResolver : IDependencyResolver
    {
        readonly IServiceLocator _serviceLocator;

        public ServiceLocatorDependencyResolver(IServiceLocator serviceLocator)
        {
            _serviceLocator = serviceLocator;
        }

        public object GetService(Type serviceType)
        {
            if (serviceType.IsInterface || serviceType.IsAbstract)
            {
                return GetInterfaceService(serviceType);
            }
            return GetConcreteService(serviceType);
        }

        private object GetConcreteService(Type serviceType)
        {
            try
            {
                // Can't use TryGetInstance here because it won’t create concrete types
                return _serviceLocator.GetInstance(serviceType);
            }
            catch (ActivationException)
            {
                return null;
            }
        }

        private object GetInterfaceService(Type serviceType)
        {
            object instance;
            return _serviceLocator.TryGetExistingInstance(serviceType, out instance) ? instance : null;
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return _serviceLocator.GetAllInstances(serviceType).Cast<object>();
        }
    }

You can find documentation on this link: https://world.episerver.com/documentation/developer-guides/CMS/initialization/dependency-injection/

#198436
Edited, Oct 29, 2018 9:26
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.