16

I read this post today about replacing Sitecores 8.2 default DI (https://medium.com/@structuredcode/replacing-the-default-di-container-in-sitecore-8-2-4e65d4956c99), but the example is for Autofac. We use SimpleInjector, but I'm sure not how to do this for SimpleInjector; does anyone have any examples?

1 Answer 1

20

The problem with the simple injector container is that they do not provide a conforming container option. They don't like it. So to replace it with Simple Injector requires a bit more effort.

In this post Habitat DI with Simple Injector - I explained how to use SI in a conforming way to register your dependencies for Habitat projects.

You could take a similar approach with replacing the default Sitecore container. Using the custom ServiceProviderBuilder from the post in the question you could do this:

public class SimpleInjectorServiceProviderBuilder
  : BaseServiceProviderBuilder
{
    protected override IServiceProvider BuildServiceProvider(IServiceCollection serviceCollection)
    {
        var container= new Container();

        // Register Sitecore services in SI
        var containerCache = new List<Type>();
        foreach (var serviceDescriptor in dependencyInjectionArgs.ServiceCollection)
        {
            // Safety check so we don't try to register the same type twice
            if (containerCache.Contains(serviceDescriptor.ServiceType))
            {
              continue;
            }
            Lifestyle siScope;
            switch (serviceDescriptor.Lifetime)
            {
              case ServiceLifetime.Singleton:
                siScope = Lifestyle.Singleton;
                break;
              case ServiceLifetime.Transient:
                siScope = Lifestyle.Transient;
                break;
              case ServiceLifetime.Scoped:
              default:
                siScope = Lifestyle.Scoped;
                break;
            }
            container.Register(serviceDescriptor.ServiceType, serviceDescriptor.ImplementationType, siScope);
            containerCache.Add(serviceDescriptor.ServiceType);
        }

        // Return service provider adaptor.
        return container.Resolve<IServiceProvider>();
    }
}

As you can see - instead of calling the .Populate method and passing the service collection in, you have to enumerate through the service collection and more manually register your services. (Please note, this is PoC and untested code :) )

1
  • Nice, thanks Richard. I'll take a look at this. We're using WebActivatorEx to wire up DI at the moment in 8.1 update 2 so my plan is to upgrade and move to using the out of the box DI hooks. Commented Oct 3, 2016 at 21:29

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.