Last active
October 26, 2023 17:59
-
-
Save zoyo23/c26ed914b77f3695a99d57895cc0ac14 to your computer and use it in GitHub Desktop.
Dynamic Inject dependency by Key
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 class Consumer | |
{ | |
private readonly IService _aService; | |
public Consumer(ServiceResolver serviceAccessor) | |
{ | |
_aService = serviceAccessor("A"); | |
} | |
public void UseServiceA() | |
{ | |
_aService.DoTheThing(); | |
} | |
} |
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
services.AddTransient<ServiceResolver>(serviceProvider => key => | |
{ | |
switch (key) | |
{ | |
case "A": | |
return serviceProvider.GetService<ServiceA>(); | |
case "B": | |
return serviceProvider.GetService<ServiceB>(); | |
case "C": | |
return serviceProvider.GetService<ServiceC>(); | |
default: | |
throw new KeyNotFoundException(); | |
} | |
}); |
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 delegate IService ServiceResolver(string key); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment