Published on, Time to read
🕒 1 min read

Optimizely / Episerver: Automatically register dependencies

Optimizely / Episerver: Automatically register dependencies

In Optimizely, dependency injection is based on the Microsoft.Extensions.DependencyInjection library by default.

You may register dependencies:

  • explicitly
    • can be done in either Startup.cs or InitializableModule
    • example of code: context.Services.AddTransient<ISomeService, SomeService>()
  • implicitly
    • by applying the [ServiceConfiguration] attribute

If you want to automate the registration of dependencies, you can use the Scrutor library. The library scans assemblies and automatically registers dependencies based on the attributes applied to the classes.

The code I'm using for the Optimizely project lands at the end of the ConfigureServices method in Startup.cs:

services.Scan(x => x.FromAssembliesOf(typeof(Startup))
                    .AddClasses(filter => filter.Where(type => !typeof(Attribute).IsAssignableFrom(type)))

Please note that RegistrationStrategy.Skip makes previous registrations take precedence over the ones made by the Scrutor.

Scrutor is, of course, not only limited to Optimizely. You can use it in any .NET project (which I recommend).