Created
November 2, 2018 16:10
-
-
Save angelo-marano/b141a79fd96f31c33a244589cec90c10 to your computer and use it in GitHub Desktop.
Service Locator IoC in Azure Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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."); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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