Since version 8, Sitecore has started focusing on cleaner and extensible architecture with more and more plug and play features. One key improvement in version 8 was introducing dependency injection within Sitecore based on .net core libraries for DI.
So if you are creating an application in Sitecore and planning to use DI, you can always make use of inbuilt DI used by Sitecore. Obvious advantage is you wont be introducing any new paths in the solution and no new libraries will be introduced keeping the solution lightweight.
So if you are creating an application in Sitecore and planning to use DI, you can always make use of inbuilt DI used by Sitecore. Obvious advantage is you wont be introducing any new paths in the solution and no new libraries will be introduced keeping the solution lightweight.
So, the obvious question - how do we do it?
I am assuming here that you have basic understanding of a Sitecore application and dependency injection fundamentals. Hence, I will focus on steps needed to enable DI in Sitecore.
- Include the following DLLs to references in your project (in Foundation layer if you are following Helix principles) - Microsoft.Extensitons.DependencyInjection, Microsoft.Extensions.DependencyInjection.Abstraction
- Create the configurator class implementing the IServiceConfigurator (I recommend to try to reuse the configurator logic from Habitat project)
public class MyServicesConfigurator : IServicesConfigurator{
public void Configure(IServiceCollection serviceCollection)
{
serviceCollection.AddScoped(typeof(IMyService), typeof(MyServiceImplementation));
serviceCollection.AddTransient(typeof(MyServiceBase), typeof(MyServiceBaseImplementation));
}
}
- Create the patch to introduce custom configurator class in the application
<configuration><sitecore>
<services>
<configurator type= "MyServicesConfigurator, MyAssembly"/>
</services>
</sitecore>
</configuration>
That's it. You can register your interface implementations now in the custom configurator class that we have created. Hope this helps you.
References -
Please like and subscribe the blog for similar updates.
Comments
Post a Comment