如何使用 Autofac 注册通用服务?

How to register generic service with Autofac?

我有一个通用服务:

public class FileDataService<T> : IFileDataService<T>
{
    public async Task<List<T>> GetListResultAsync(IFileSearcher<T> searcher)
    {
        return await searcher.GetResultsAsync();
    }
}

我正在尝试注册:

builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
    .AsClosedTypesOf(typeof(IFileDataService<>));
builder.RegisterType<SampleService>().As<ISampleService>();
builder.AddMediatR(this.GetType().Assembly);

builder.Register(c => UmbracoContext.Current).AsSelf();

MediatR 处理程序的依赖注入中使用它;

public class QueryHandler : IRequestHandler<Query, Result>
{
    private readonly IFileDataService<ResultModel> _fileDataService;
    private readonly ISampleService _sampleService;
    private readonly UmbracoHelper _umbHelper;

    public QueryHandler(
        IFileDataService<ResultModel> fileDataService, ISampleService sampleService)
    {
        _fileDataService = fileDataService;
        _sampleService = sampleService;
        _umbHelper = new UmbracoHelper(UmbracoContext.Current);
    }

它告诉我处理程序没有正确构造:

Error constructing handler for request of type MediatR.IRequestHandler

如何使用 Autofac & MediatR 在 .NET 4.7.2 中正确注册和使用通用服务?

我认为你的问题是因为 FileDataService<T> 不是 封闭类型,所以 .AsClosedTypesOf(typeof(IFileDataService<>)); 不会选择它。

你要做的是使用 Autofac RegisterGeneric 方法将 FileDataService<T> 注册为通用组件;这无法通过程序集扫描机制完成。

builder.RegisterGeneric(typeof(FileDataService<T>)).As(typeof(IFileDataService<>));

文档:https://autofaccn.readthedocs.io/en/latest/register/registration.html#open-generic-components