Sitecore Dependency Injection Part - 1
Introduction:
In this Article we will try to see how we can implement Dependency Injection with examples. We will continue building on the the glass mapper sample created in our Previous blog. With Inheritance and Interface, we achieve loose coupling, but dependency injection (DI) take it one step ahead. in summary DI takes away all the mapping (which Interface will create which instance) at configuration level.
Implementation:
1 - Setup IServicesConfigurator:
First thing to do is create a IServicesConfigurator. At this point it is a bit tricky part. If this is for the first time you are adding "IServicesConfigurator", You will get first error message stating reference need to be added for "Sitecore.DependencyInjection" after this, the warning Quigley line will still remain on "IServicesConfigurator". If you hoverover it, you will see it states "needs Microsoft.Extensions.DependencyInjection to work but not installed". Here is the catch, it states manage Nuget package with latest update and it dependencies. at this point of time there is no matching "Microsoft.Extensions.DependencyInjection" for latest Service Configurator (version 7.0.0).
But if you hover over "IServicesConfigurator", it states which version of "Microsoft.Extensions.DependencyInjection" he is looking for, just install that version from nuget package manager.
Given below is the code snap short.
It is very simple but yet very useful step. Add Your Controller as shown in the below Snap short. If you miss this you will get error stating Controller not found. If still this does not ring the bell, you will find it when you see controller code for DI.
In fig-1, we have mapped 4 interfaces and one controller. now we will use constructor injection to further loosely couple our implementation.
(given below is the code snap short of Controller.)
Comments
Post a Comment