如何在Startup类之外访问IServiceCollection和/或IServiceProvider?

时间:2018-04-20 08:20:02

标签: dependency-injection .net-4.0 .net-core

我在.Net Farmework 4.6.2类库中使用Microsoft.Extensions.DependencyInjection。如何从实例化的源代码外部访问IServiceCollection和/或IServiceProvider,例如Main()?我可以创建一个静态类,在一个单独的类库中公开这个属性并引用它,但我想知道是否还有其他更好的方法来实现这个目标。 .Net Framework具有ServiceLocator.Current.GetInstance。 Microsoft.Extensions.DependencyInjection中是否有类似的东西?任何建议和见解都表示赞赏。

3 个答案:

答案 0 :(得分:1)

没有单身“实例”。您可以根据需要创建任意数量的服务提供商。您可以正常将其作为参数传递。

您可以IServiceProvider注入到任何由它实例化的类中。只需将其添加为构造函数参数即可。

答案 1 :(得分:0)

在大多数情况下,IServiceProvider 不应直接使用,因为它会导致Service Locator antipattern而不是依赖注入模式。

但是,在某些情况下确实有道理。特别是在多线程WPF或Blazor应用程序中,您需要多个作用域进行数据库访问。为此,您只需将IServiceProvider注入从其创建的类的构造器中即可:

public sealed class ServiceProviderResolver
{
    public ServiceProviderResolver(IServiceProvider serviceProvider)
    {
        ServiceProvider = serviceProvider;
    }

    public IServiceProvider ServiceProvider { get; }
}

比您可以根据需要创建新的范围服务:

public static IDisposable Scoped<T>(this IServiceProvider scopeFactory, out T context)
{
    var scope = scopeFactory.CreateScope();
    var services = scope.ServiceProvider;
    context = services.GetRequiredService<T>();
    return scope;
}

示例:WPF用户控件

假设我们正在使用:

public partial class MyWPFControl : UserControl, IViewFor<MyWPFControlViewModel>
{
    private IServiceProvider ServiceProvider { get; }

    public MyWPFControl()
    {
        InitializeComponent();

        // Use dependency resolver to get the service provider
        ServiceProvider = Splat.Locator.Current
            .GetService<ServiceProviderResolver>()
            .ServiceProvider;

        this.WhenActivated(d => {
            ActivateCustomerIdSelected(d);
            // ...
        });
    }

    private void ActivateCustomerIdSelected(d)
    {
        this.WhenAnyValue(vm => vm.CustomerId)
            .Where(id => id != null)
            .Select(_ => this)
            .SelectMany(async (vm, ct) => {
                // Make a database query in a dedicated scope
                // This way we can isolate the context 
                // Such that other threads won't interfer with the context
                using(var scope = ServiceProvider.Scoped<IMyDbContext>(out var context))
                {
                    return await context.Customers
                        .Where(c => c.Id == vm.CustomerId)
                        .AsNoTracking()
                        .SingleOrDefaultAsync(ct)
                        .ConfigureAwait(false);
                }
            })
            .ObserveOn(RxApp.MainThreadScheduler)
            // execute the DB query on the TaskPool
            .SubscribeOn(RxApp.TaskPoolScheduler) 
            // Handle the result 
            // Note: we are still on the task pool here
            // you might need DynamicData.SourceCache 
            // or DynamicData.SourceList when handling
            // multiple results
            .Subscribe(customer => { /* ... */ })
            .DisposeWith(d);
        }
    }

    // ...

    [Reactive] public Guid? CustomerId { get; set; }

    // ...
}

答案 2 :(得分:0)

IServiceProvider 不同的是,IServiceCollection 不能注入到类构造函数中。

正如许多人所说,您应该避免直接使用它们。但是如果您确实需要IServiceCollection 这样做,您可以创建一个“提供程序”,例如:

    public interface IServiceCollectionProvider 
    {
        IServiceCollection ServiceCollection { get; }
    }

    public sealed class ServiceCollectionProvider: IServiceCollectionProvider
    {
        public ServiceCollectionProvider(IServiceCollection serviceCollection)
        {
            ServiceCollection = serviceCollection;
        }

        public IServiceCollection ServiceCollection { get; }
    }

注册:

services.AddSingleton<IServiceCollectionProvider>(new ServiceCollectionProvider(services));

使用:

    public class YourController : Controller
    {
        private readonly IServiceProvider _provider;
        private readonly IServiceCollection _services;

        public YourController (IServiceProvider provider, IServiceCollectionProvider serviceCollectionProvider)
        {
            _provider = provider;
            _services = serviceCollectionProvider.ServiceCollection;
        }
    }