Search code examples
c#.net-coreautofacioc-container

Autofac cannot resolve my Registered generic service


I've registered my generic interface in Autofac, but as I resolve it exception is thrown.

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();
    }

Service Registration

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

Resolve Service

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;
    }

Solution

  • I got the solution, thank to @Nkosi. As I return ICommand from GetCommandByDescriptor(string descriptor) the type T in Dispatch Method would be from ICommand type which is actually not registered, I should return a type which have implemented ICommand e.g. ListOfDirectoryCommand.

    As well I go like this:

    invoker.Dispatch((dynamic)command);
    

    So the type of command would be specified in run time.