【问题标题】:Autofac DI migration to ASP.NET Core DIAutofac DI 迁移到 ASP.NET Core DI
【发布时间】:2020-06-09 10:43:09
【问题描述】:

我有使用 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>();
    }
}

根据类型动态选择Handler

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?

【问题讨论】:

  • 您的问题需要更多关注。你试过什么?什么不起作用?您迁移时遇到困难的部分是什么?请尽可能具体。
  • 实际上我已经按照里卡多的建议做了同样的事情,但仍然出现错误:Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding on a null reference
  • 既然您似乎需要批量注册,那您为什么还要从 Autofac 切换到 MS.DI。 Autofac 有内置的批量注册支持,而 MS.DI 没有。

标签: c# asp.net-core dependency-injection autofac


【解决方案1】:

注册:

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

【讨论】:

  • 我已经尝试过了,但是我得到了一个错误:Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding on a null reference
  • 啊,你也需要注册IQueryHandler
  • 是的,但是我有 8 到 10 个处理程序,而且注册很多,因为我必须注册每个处理程序。但是对于 Autofac,我只能在 QueryDispatcher 中执行一次
  • 不,你注册的是开放式
  • 我的意思是,typeof(IQueryHandler)
猜你喜欢
  • 1970-01-01
  • 2018-12-15
  • 1970-01-01
  • 2021-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-26
  • 1970-01-01
相关资源
最近更新 更多