.net core 如何从Autofac迁移到Microsoft依赖项注入?

.net core 如何从Autofac迁移到Microsoft依赖项注入?,.net-core,dependency-injection,autofac,.net Core,Dependency Injection,Autofac,我不再在.NET Core 3.1应用程序中使用Autofac和Microsoft依赖项注入 如何在DI中执行相同的操作: builder.RegisterAssemblyTypes(assembly) .AsClosedTypesOf(typeof(IEventHandlerRabbitMq<>)) .InstancePerDependency(); builder.RegisterType<BusPublisher>().As<IBusPubl

我不再在.NET Core 3.1应用程序中使用Autofac和Microsoft依赖项注入

如何在DI中执行相同的操作:

builder.RegisterAssemblyTypes(assembly)
    .AsClosedTypesOf(typeof(IEventHandlerRabbitMq<>))
    .InstancePerDependency();

builder.RegisterType<BusPublisher>().As<IBusPublisher>().InstancePerDependency();

builder.RegisterInstance(DefaultJaeger.Create())
    .As<ITracer>()
    .SingleInstance()
    .PreserveExistingDefaults();
builder.RegisterAssemblyTypes(程序集)
.AsClosedTypesOf(typeof(ieventhandlerabbitmq))
.InstancePerDependence();
builder.RegisterType().As().InstancePerDependence();
builder.RegisterInstance(DefaultJaeger.Create())
.As()
.SingleInstance()
.preserveinexistingdefaults();
如前所述,您需要对
AsClosedTypesOf
使用反射。下面是一些示例,说明如何实现这一点:

public static void RegisterGenerics(this IServiceCollection services, Assembly assembly, Type genericType)
    {
        AppDomain.CurrentDomain.GetAssemblies()
            .FirstOrDefault(a => a.FullName == assembly.FullName)
            .GetTypes()
            .Where(x => x.IsAssignableFrom(genericType) && !x.IsAbstract && !x.IsInterface)
            .ToList()
            .ForEach(t =>
            {
                services.AddTransient(genericType, t);
            });
    }
然后您可以在startup类中使用它:

services.RegisterGenerics(Assembly.GetExecutingAssembly(), typeof(IEventHandler<>));
services.RegisterGenerics(Assembly.getExecutionGassembly(),typeof(IEventHandler));

在MS.DI中没有与注册SemblyTypes等效的代码。您必须显式注册每个实现,或者必须使用反射查找并注册所有实现。顺便说一句,您是否知道可以在.NET核心应用程序中继续使用Autofac?Assembly.GetExecutionGassembly().GetTypes().Where(item=>item.GetInterfaces().Where(i=>i.IsGenericType).Any(i=>i.GetGenericTypeDefinition()==typeof(ieventhandlerabbitMQ))&&!item.isStract&&!item.IsInterface.ToList().ForEach(assignedTypes=>{var serviceType=assignedTypes.GetInterfaces()。首先(i=>i.GetGenericTypeDefinition()==typeof(ieventhandlerabbitMQ));types.Add(assignedTypes);services.AddScoped(serviceType,assignedTypes);});我可以改用GetExecutionGassembly吗?