- Published on, Time to read
- 🕒 1 min read
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
orInitializableModule
- example of code:
context.Services.AddTransient<ISomeService, SomeService>()
- can be done in either
- implicitly
- by applying the
[ServiceConfiguration]
attribute
- by applying the
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)))
.UsingRegistrationStrategy(RegistrationStrategy.Skip)
.AsImplementedInterfaces());
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).