【发布时间】: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