I use .NET Core WebAPI with dependency injection and multiple authentication schemas (http basic, access keys, JWT). I inject some business services which require some authenticated user data. If user is authenticated by any of auth middleware, DI works fine. If the user is not authenticated, DI cannot resolve some services. I need DI to return null.
How is that possible? Code bellow will result in exception, null is not allowed as result.
services.AddTransient<IMasterRepository>(serviceProvider =>
{
var _serviceFactory = new RepositoriesFactory(Configuration);
if (!Authenticated)
{
return null;
}
return _serviceFactory.CreateMasterRepository();
});
Also, I cannot return 401 in auth middleware, because another middleware may success (expl: cannot return 401 in http basic auth middleware because next one, JWT, may success)
Also, I cannot add "authentication required" check after all auth middlewares because some controllers are public (no authentication / dependency injection required).
Any advice? Thanks!
?(C# 8)?