Skip to content

Instantly share code, notes, and snippets.

@AThraen
Created September 4, 2018 19:48
Show Gist options
  • Select an option

  • Save AThraen/6794d545f921476388c4667dd51ac1ed to your computer and use it in GitHub Desktop.

Select an option

Save AThraen/6794d545f921476388c4667dd51ac1ed to your computer and use it in GitHub Desktop.
Setting up correct dependency injection in Episerver CMS site not based on Alloy.
using System.Web.Mvc;
using EPiServer.Framework;
using EPiServer.Framework.Initialization;
using EPiServer.ServiceLocation;
using EPiServer.Web.Mvc;
using EPiServer.Web.Mvc.Html;
namespace DependencyInjection
{
[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)
{
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using EPiServer.ServiceLocation;
namespace DependencyInjection
{
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>();
}
}
}
@javafun

javafun commented Apr 13, 2019

Copy link
Copy Markdown

_serviceLocator.GetAllInstances(serviceType) will return IEnumerable. Do you still need to cast to object again?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment