Skip to content

Instantly share code, notes, and snippets.

@angelo-marano
Created November 2, 2018 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angelo-marano/b141a79fd96f31c33a244589cec90c10 to your computer and use it in GitHub Desktop.
Save angelo-marano/b141a79fd96f31c33a244589cec90c10 to your computer and use it in GitHub Desktop.
Service Locator IoC in Azure Function
public interface IWireCharacterFactory {
string GetWireCharactor();
}
public class TheBestWireCharacterFactory : IWireCharacterFactory {
public string GetWireCharactor() {
return "Bodie"; //Because he was.
}
}
public static class MyFirstFunction
{
[FunctionName("MyFirstFunction")]
private static IServiceLocator ServiceLocator = new ServiceLocator();
static MyFirstFunction() {
ServiceLocator.Register<IWireCharacterFactory>(new TheBestWireCharacterFactory());
}
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var factory = ServiceLocator.Resolve<IWireCharacterFactory>();
string name = factory.GetWireCharactor();
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Something was really wrong.");
}
}
public interface IServiceLocator {
//This is real bad, don't use this
//There's so much missing from this
void Register<T>(T t);
T Resolve<T>();
}
public class ServiceLocator : IServiceLocator
{
//This is worse than the above interface. Seriously, don't use this
private readonly Dictionary<Type, object> _types = new Dictionary<Type, object>();
public void Register<T>(T t)
{
_types.Add(typeof(T), t);
}
public T Resolve<T>()
{
var obj = _types[typeof(T)];
return (T)obj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment