我正在为一个奇怪的案例而苦苦挣扎。我有一个 .NET Core 控制台应用程序,其设置如下:
private static async Task Main(string[] args)
{
var runAsService = !(Debugger.IsAttached || args.Contains("console"));
var builder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddLogging(loggingBuilder => { loggingBuilder.AddConsole(); });
services.AddGatewayServers();
services.AddHostedService<GatewayService>();
});
if (runAsService)
await builder.RunServiceAsync();
else
await builder.RunConsoleAsync();
}
然后我对IServiceCollection这个设置进行了扩展,AddGatewayServers()如下所示:
public static void AddGatewayServers(this IServiceCollection services)
{
services.AddTransient<IGatewayServer, Server1>();
services.AddTransient<IGatewayServer, Server2>();
services.AddTransient<Func<ServerType, IGatewayServer>>(provider => key =>
{
switch (key)
{
case ServerType.Type1: return provider.GetService<Server1>();
case ServerType.Type2: return provider.GetService<Server2>();
default: return null;
}
});
}
然后在我的课上我注入这样的依赖:
private readonly Func<ServerType, IGatewayServer> _gatewayAccessor;
public GatewayServerCollection(Func<ServerType, IGatewayServer> gatewayAccessor)
{
_gatewayAccessor = gatewayAccessor;
}
但是当我_gatewayAccessor稍后调用它GatewayServerCollection来获取它的实例时,IGatewayServer它会返回null。我这样称呼它:
var server = _gatewayAccessor(ServerType.Type1);
我错过了什么?
aluckdog
相关分类