dotnet / dotnet/command-line-api
Expansion of BindingContext
- Dominant language
- C#
- Stars
- 3.7k
- Forks
- 428
- PR merge metrics
- No merged PRs in 30d
Description
I've been building some simple tools to test the framework and am very impressed with how expandable it is. I really like that it provides a means of exposing a service collection via BindingContext and ServiceProvider to be used by commands. I currently use it as a way to abstract away a DI container from my commands, that way my commands are only concern with binding args and calling into a service. Using middle ware to only build the DI container on a successful parse. The only concern I have about the current implementation is that to naively or lazily populate the BindingContext, I need to enumerate through all services in the container adding them to the BindingContext to make them available to my commands. It seems that a better way to handle this could be to add a means to add a fallback factory to the BindingContext that will be used if no factory is found in the ServiceProvider via the BindingContext the fallback can be called to resolve the service.
For example I am thinking something like this following.
```C#
internal class ServiceProvider : IServiceProvider
{
...
private readonly List> _fallbackFactories = new();
...
public void AddFallback(Func fallback) => _fallbackFactories.Add(fallback);
public object? GetService(Type serviceType)
{
if (_services.TryGetValue(serviceType, out var factory))
{
return factory(this);
}
foreach (var fallback in _fallbackFactories)
{
var result = fallback(serviceType);
if (result is not null) return result;
}
return null;
}
}
public sealed class BindingContext : IServiceProvider
{
...
public void AddFallback(Func fallback) => ServiceProvider.AddFallback(fallback);
...
}
```
The AddFallback method would need to be exposed in BindingContext, but otherwise is fairly self contained. The only real issue I see with this is that it under minds ServiceProvider.AvailableServiceTypes since there will now be services that are resolvable that can not be enumerated since the fallback does not expose what it can produce. I am personally not to concern with this since it seems like the BindingContext is the only class that uses ServiceProvider and it does not expose ServiceProvider or that property.
What are everyone's thoughts on this?
Contributor guide
Assessment
This issue has not been assessed yet.