在Singleton中使用范围服务可以吗?

时间:2020-10-19 03:52:47

标签: .net dependency-injection

是否可以将 Scoped IServiceProvider传递给 Singleton

上下文是我有一个 Singleton IMediaLibraryObservable ,它具有内部观察者列表。这是为了触发钩子,例如OnAdding,OnDeleting等。

观察者是可以实现所需内容并重新使用注册服务的接口。为了使他们能够访问所需的内容,将 Scoped IServiceProvider作为方法的一部分进行传递。

代码如下:

启动注册:

services.AddSingleton<IMediaLibraryObservable<MediaEventInfo>, MediaLibraryObservable>();

可观察的界面

public interface IMediaLibraryObservable
{
    Task OnAdding(IServiceProvider _serviceProvider, MediaEventInfo info);
    ...

OnAdding的实现

public async Task OnAdding(IServiceProvider _serviceProvider, MediaEventInfo info)
        {
            foreach (var observer in observers)
                await observer.OnAdding(_serviceProvider, info);
        }

观察者实现:

public async Task OnAdding(IServiceProvider _serviceProvider, MediaEventInfo info)
        {
            using (var ms = new MemoryStream())
            {
                await info.File.CopyToAsync(ms);
                var path = await ServiceProviderHelpers.GetService<IBlobStorage>(_serviceProvider).WriteAsync(info.ContentItem.InternalName, ms);

可观察的触发器(范围IServiceProvider传递到Singleton可观察的):

private readonly IMediaLibraryObservable _mediaLibraryObservable;
private readonly IServiceProvider _serviceProvider;

public MediaLibraryService(IMediaLibraryObservable mediaLibraryObservable, IServiceProvider serviceProvider) {
  _mediaLibraryObservable = mediaLibraryObservable;
  _serviceProvider = serviceProvider;
}

public async Task < bool > UploadBlob(string fullPath, FormFileDto file) {
  ...
  await _mediaLibraryObservable.OnAdding(_serviceProvider, info);
  ...
}

0 个答案:

没有答案