I've created a small service locator which I will use in ActionFilterAttributes and IHttpModules. At the time of Writing I'm using simple injector, but I want to make it container agnostic. The idea is to let consumers of my framework inject an optional configuration to my classes, e.g:
container.RegisterInstance<IConfiguration>(() => new CustomConfiguration());
Below is my current draft. Please feel free to suggest any improvements. A thing that came to mind is how well it will treat a service with scoped lifestyle. For example, if I request a service in a filter's OnActionExecuting, will the container understand that the service is requested in a web request scope, or do I have to explicitly create a scope? The configuration will be a singelton so that won't be a problem with that specific dependency, just asking out of curiosity.
public class ServiceLocator
{
public static T GetService<T>()
{
return (T)GetDependencyScope().GetService(typeof(T));
}
private static IDependencyScope GetDependencyScope()
{
if (HttpContext.Current.Items["MS_HttpRequestMessage"] is HttpRequestMessage httpRequestMessage)
{
return httpRequestMessage.GetDependencyScope();
}
return GlobalConfiguration.Configuration.DependencyResolver;
}
}