Same instance for multiple services
I believe this can only be achieved with code registration:
var implementation = new ServiceImplementation();
serviceCollection.AddSingleton<IService>(provider => implementation);
serviceCollection.AddSingleton<IExtendedService>(provider => implementation);
In case ServiceImplementation
has its own dependencies, you will need to instantiate it from the container as well. Here's a trick you can use:
serviceCollection.AddSingleton<IService, ServiceImplementation>();
serviceCollection.AddSingleton<IExtendedService>(
provider => (ServiceImplementation)provider.GetService(typeof(IService)));
Below you can find more general details that I typed in before fully understanding the question :)
XML registration
If you're using XML registration, just add a .config patch file with the following contents:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<services>
<register
serviceType="[Namespace].IService, [Assembly]"
implementationType="[Namespace].ServiceImplementation, [Assembly]"
lifetime="Singleton" />
<register
serviceType="[Namespace].IExtendedService, [Assembly]"
implementationType="[Namespace].ServiceImplementation, [Assembly]"
lifetime="Singleton" />
</services>
</sitecore>
</configuration>
Code registration
You should use Sitecore configurators to register dependencies from code.
There are many available registration methods. Here's an example with a singleton dependency:
serviceCollection.AddSingleton<IExtendedService, ServiceImplementation>;
A transient example:
serviceCollection.AddTransient<IService>(provider => new ServiceImplementation());
To see the complete list of available registration methods, decompile the class ServiceCollectionServiceExtensions
in the assembly Microsoft.Extensions.DependencyInjection.Abstractions
. The main variations are:
AddTransient<...>(...)
AddScoped<...>(...)
AddSingleton<...>(...)
Add(Type, Type, ServiceLifetime)
Add(Type, Func<IServiceProvider, object>, ServiceLifetime)
Dependency lifetime
Regardles of which registration method you choose, remember to specify an appropriate lifetime scope. The supported options are:
Singleton
Scoped
Transient
Further reading