Search code examples
c#dependency-injectionautofac

Autofac is resolving duplicate instances


I want to get a list of all validators of a particular command using Autofac. I have created an interface

    public interface IValidate<T>
    {
        void Validate(T command);
    }

And I have implemented 2 validators for this interface

    public class ValidateRule1 : IValidate<CreateEnrollmentCommand>
    {
        public void Validate(CreateEnrollmentCommand command)
        {
        }
    }

    public class ValidateRule2 : IValidate<CreateEnrollmentCommand>
    {
        public void Validate(CreateEnrollmentCommand command)
        {
        }
    }

I am injecting these validators in an IEnumerable like this

public class MyCommandHandler
{
    private readonly IRepository _repository;
    private readonly IEnumerable<IValidate<CreateEnrollmentCommand>> _validators;

    public MyCommandHandler(IEnrollmentRepository enrollmentRepository, IEnumerable<IValidate<CreateEnrollmentCommand>> validators)
    {
        _enrollmentRepository = enrollmentRepository;
        _validators = validators;
    }
 }

Here is my Autofac Configuration

    public class AutofacModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            // Register API Assembly
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .AsImplementedInterfaces();

            // Register Data Access
            var api = typeof(CreateStudentCommand).Assembly;
            builder.RegisterAssemblyTypes(api)
                .AsImplementedInterfaces();

            // Register Data Access
            var dataAccess = typeof(StudentRepository).Assembly;
            builder.RegisterAssemblyTypes(dataAccess)
                .AsImplementedInterfaces();


            builder
                .RegisterType<Mediator>()
                .As<IMediator>()
                .InstancePerLifetimeScope();

            builder.Register<ServiceFactory>(context =>
            {
                var c = context.Resolve<IComponentContext>();
                return t => c.Resolve(t);
            });

            builder.RegisterAssemblyTypes(typeof(CreateStudentCommand).GetTypeInfo().Assembly).AsImplementedInterfaces(); // via assembly scan
        }
    }

I am expecting two validators to be injected by Autofac, but it is actually injecting 2 instances of each validator. I am getting total of 4 validator instances in the IEnumerable property. Any idea what am I doing wrong?

Edit: The IValidate interface and the validators are all located in the same assembly as pointed out by @Lasse V. Karlsen


Solution

  • You have several calls that register all types in an assembly, in particular I would check:

    • The duplicate registration of all types in the assembly that contains the CreateStudentCommand type
    • Whether all the types used to identify "all types in assembly" are in separate assemblies