Dependency injection
Describes dependency injection in Optimizely Configured Commerce.
Dependency injection (DI) in Optimizely Configured Commerce is based on the DI framework in ASP.NET Core located in the Microsoft.Extensions.DependencyInjection API.
Configured Commerce uses Grace for .NET Core 6.0 and above and Unity for .NET 4.8 by default. The container registration process starts in the BootStrapper, which is called from the SiteStartup.cs class in .NET 4.8 and the UseCommerce extension method in .NET Core.
Registration of dependencies
You can register a class in the IOC container by adding an IDependency and an IExtension interface. This allows the DependencyRegistrar class to find and register the class at startup. The DependencyRegistrar class goes through the app domain assemblies and registers all implementations that it finds with these interfaces.
The default lifetime is per request. You can change the timeline to singleton or transient lifetime by adding an ISingletonLifetime or ITransientLifetime interface to the dependency.
You can register multiple implementations for a single interface by adding the IMultiInstanceDependency interface to the implementation. This automatically uses the class name as the registration name. Alternatively, you can use the DependencyName attribute to register under a custom name.
Customization
You can add attributes to the dependency implementation to change its behavior:
- DependencyName – Sets the name that the dependency is registered as in the container.
- DependencyOrder – Changes the order in which the dependency is loaded from the container. This defaults to 999. When registering implementations for an interface, the attribute goes in sort order from low to high, and the highest one (if it is not a named registration) overwrites lower ones in the IOC container.
- DependencyExclude – Excludes the dependency from being registered, such as for base classes.
- DependencySystemSetting – Locates a system setting with the specified name and a matching value and registers that dependency.
Locate dependencies
You should use dependency injection through constructors. You can either set the dependency directly as a parameter in the constructor or set IDependencyLocator as a parameter and use the methods on that interface to get dependencies.
You can get dependencies in .NET Core through context such as HttpContext.RequestServices.
Named registrations should have a factory with a IDependencyLocator injected which can do the resolution by name.
Updated 7 months ago