I should probably start this post with a caveat saying, "don't do this... unless you really, really have to!" With Umbraco 9, built on .NET 5, we have support for the dependency injection design pattern , and where possible, the recommedation is to use that, to promote testability and other best practices. Within the Umbraco CMS source code though, and also in the add-on products Forms and Deploy, we have found it necessary to use service location in a couple of instances. Primarily, to avoid breaking changes. For example, when a public class requires a new dependency, we don't just add it to the constructor as that would potentially break integrations that are already using it. Instead we obsolete the existing constructor, create a new one with the additional parameter, and have the original constructor delegate to the new one - using service location to provide the parameter for the added dependency. In code it looks like this: To use, you need to be ref...
Senior Developer and head of DXP at Umbraco. Previously with Zone, building solutions primarily on .NET and using Umbraco, EPiServer and Sitecore CMS. This blog is used as a repository for various tips, tricks, issues and impressions drawn from the use of technology my work and interests. All words are my own.