Autofac 无法解析我注册的通用服务

Autofac cannot resolve my Registered generic service

我已经在 Autofac 中注册了我的通用接口,但是当我解决它时抛出了异常。

Autofac.Core.Registration.ComponentNotRegisteredException: The requested service 'MyCLI.Command.ICommandHandler`1[[MyCLI.Command.ICommand, MyCLI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' has not been registered.

To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.

Program.cs

    static void Main(string[] args)
    {
        ContainerBuilder builder = new ContainerBuilder();

        var container = builder.RegisterTypes();
        var invoker = new Invoker(container);
        var command = TypeHelper.GetCommandByDescriptor("LS");
        invoker.Dispatch(command);

        Console.Read();
    }

服务注册

    public static IContainer RegisterTypes(this ContainerBuilder builder)
    {
        builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
            .AsClosedTypesOf(typeof (ICommandHandler<>)).AsImplementedInterfaces();
        return builder.Build();
    }

解决服务

public class Invoker : IInvoker
{
    private readonly IContainer container;
    public Invoker(IContainer container)
    {
        this.container = container;
    }

    public void Dispatch<T>(T command) where T : ICommand
    {
        //if (!container.IsRegistered(typeof(ICommandHandler<>))) return;
        var candidate = container.Resolve<ICommandHandler<T>>();
        candidate.Execute(command);
    }
}

GetCommandByDescriptor

    public static ICommand GetCommandByDescriptor(string descriptor)
    {
        var classes = GetAllCommands();
        var command = classes.First(x => x.GetType()
                        .GetCustomAttributes<CommandDescriptorAttribute>().First().CommandName.Equals(descriptor, StringComparison.OrdinalIgnoreCase));
        return command;
    }

感谢@Nkosi,我得到了解决方案。 因为我 return ICommand 来自 GetCommandByDescriptor(string descriptor) 调度方法中的类型 T 将来自 ICommand 实际上未注册的类型,我应该 return已实现 ICommand 的类型,例如ListOfDirectoryCommand.

我也是这样走的:

invoker.Dispatch((dynamic)command);

因此 command 的类型将在 运行 时间指定。