XConnect offers you the possibility to register types for Dependency Injection, by using configuration files. Make sure your configuration file starts with sc.
Make sure the service node (YourServiceNameMustBeUnique) is unique. This does not have to represent the name of your service and can be filled in to your own liking.
You can use either Transient or Singleton for your lifetime, the default is Singleton.
An example configuration file is shown below.
<?xml version="1.0" encoding="utf-8"?> <Settings> <Sitecore> <XConnect> <Services> <YourServiceNameMustBeUnique> <Type>YourNameSpace.YourConcreteType, YourAssembly</Type> <As>YourNameSpace.YourInterface, YourAssembly</As> <LifeTime>Transient</LifeTime> </YourServiceNameMustBeUnique> </Services> </XConnect> </Sitecore> </Settings>
Access to the ServiceCollection
If you have complicated registrations, or if you require direct access to the ServiceCollection, for example; to use serviceCollection.AddHttpClient()
, then luckily there’s a way!
You can add a registration as shown in the example above, and create a custom implementation of the Sitecore.XConnect.DependencyInjection.Abstractions.IXConnectServicesConfiguration interface.
The contents of this interface are as follows:
using Microsoft.Extensions.DependencyInjection; using System; namespace Sitecore.XConnect.DependencyInjection.Abstractions { [CLSCompliant(false)] public interface IXConnectServicesConfiguration { void ConfigureServices(IServiceCollection services); } }
As you can see in the code snippet above, theres a method that has the IServiceCollection passed as an argument.
Example
I’ve created an example that adds the HttpClient to the ServiceCollection. The IXConnectServicesConfiguration interface can be found in the Sitecore.XConnect.DependencyInjection nuget package.
sc.MyServiceConfiguration.xml
<?xml version="1.0" encoding="utf-8"?> <Settings> <Sitecore> <XConnect> <Services> <MyServiceConfiguration> <Type>Example.MyServiceConfiguration, Example</Type> <As>Sitecore.XConnect.DependencyInjection.Abstractions.IXConnectServicesConfiguration, Sitecore.XConnect.DependencyInjection</As> <LifeTime>Singleton</LifeTime> </MyServiceConfiguration> </Services> </XConnect> </Sitecore> </Settings>
MyServiceConfiguration.cs
using Microsoft.Extensions.DependencyInjection; using Sitecore.XConnect.DependencyInjection.Abstractions; namespace Example { public class MyServiceConfiguration : IXConnectServicesConfiguration { public void ConfigureServices(IServiceCollection services) { services.AddHttpClient(); } } }