为什么TryAddTransient不返回IServiceCollection?

时间:2019-05-30 10:35:35

标签: c# design-patterns dependency-injection .net-core

大多数Microsoft Dot Net Core依赖注入静态扩展都返回IServiceCollection,例如AddTransient

返回IServiceCollection可以流畅地建立依赖关系:

services
    .AddTransient<IThing,Thing>()
    .AddTransient<IOtherThing,OtherThing>()

但是这些的TryAdd变体返回空,例如TryAddTransient。这很麻烦,因为它破坏了方法链接方法。

我想不出采用这种方式设计API的原因,但我怀疑这是一个遗漏。我是否缺少某些内容,为什么它返回null?

3 个答案:

答案 0 :(得分:0)

您可以使用笨拙的命名方法来避免冲突:

public static class ServiceCollectionTryAddExtensions
{
    public static IServiceCollection AddTransientIfNotRegistered(this IServiceCollection collection,
        Type type)
    {
        collection.TryAddTransient(type);
        return collection;
    }

    public static IServiceCollection AddTransientIfNotRegistered(this IServiceCollection collection,
        Type service,
        Func<IServiceProvider, object> implementationFactory)
    {
        collection.TryAddTransient(service, implementationFactory);
        return collection;
    }

    public static IServiceCollection AddTransientIfNotRegistered<TService, TImplementation>(
        this IServiceCollection collection)
        where TService : class where TImplementation : class, TService
    {
        collection.TryAddTransient<TService,TImplementation>();
        return collection;
    }

    // Add more overloads
}

答案 1 :(得分:-1)

所有TryXXX方法的模式是,如果该方法成功,则返回true,否则返回false,这就是为什么它不返回IServiceCollection的原因。例如,请参阅Int32.TryParse,DateTime.TryParse等。您是对的,此方法确实违反了预期的约定。也许您可以向Microsoft提出要在GitHub上进行修复的票证,尽管这将是一个重大突破。

答案 2 :(得分:-1)

查看source code TryAddTransient和所有其他添加方法都使用TryAdd方法,该方法不返回任何值。虽然我不同意它应该返回服务集合,但是布尔值会很好(遵循Microsoft约定)。 我想这可以作为一种更改提出。但是也许有一个很好的理由,他们没有增加返回值。