Autofac DI迁移到ASP.NET Core DI

问题描述 投票:0回答:1

我具有使用autofac IComponentContext Resolve解析服务的功能

Startup.cs

 public void ConfigureContainer(ContainerBuilder builder)
    {
        builder.RegisterAssemblyTypes(Assembly.GetEntryAssembly())
          .AsImplementedInterfaces();
        builder.AddDispatchers();
    }

builder.AddDispatchers():

 public static class Extensions
{
    public static void AddDispatchers(this ContainerBuilder builder)
    {
        builder.RegisterType<CommandDispatcher>().As<ICommandDispatcher>();
        builder.RegisterType<Dispatcher>().As<IDispatcher>();
        builder.RegisterType<QueryDispatcher>().As<IQueryDispatcher>();
    }
}

根据类型动态选择处理程序

public class QueryDispatcher : IQueryDispatcher
{
    private readonly IComponentContext _context;

    public QueryDispatcher(IComponentContext context)
    {
        _context = context;
    }

    public async Task<TResult> QueryAsync<TResult>(IQuery<TResult> query)
    {
        var handlerType = typeof(IQueryHandler<,>)
            .MakeGenericType(query.GetType(), typeof(TResult));

        dynamic handler = _context.Resolve(handlerType);

        return await handler.HandleAsync((dynamic)query);
    }
}

我应该怎么做才能将其迁移到内置的ASP.NET Core DI?

c# asp.net-core dependency-injection autofac
1个回答
0
投票

注册:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<ICommandDispatcher, CommandDispatcher>();
    services.AddScoped<IDispatcher, Dispatcher>();
    services.AddScoped<IQueryDispatcher, QueryDispatcher>();
}

注入:

public class QueryDispatcher : IQueryDispatcher
{
    private readonly IServiceProvider _serviceProvider;

    public QueryDispatcher(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public async Task<TResult> QueryAsync<TResult>(IQuery<TResult> query)
    {
        var handlerType = typeof(IQueryHandler<,>)
            .MakeGenericType(query.GetType(), typeof(TResult));

        dynamic handler = _serviceProvider.GetService(handlerType);

        return await handler.HandleAsync((dynamic)query);
    }
}

注意:我使用的是生存期作用域,因为您没有提供有关所需生存期的任何指示,但是您也可以使用AddSingletonAddTransient

© www.soinside.com 2019 - 2024. All rights reserved.