Tejinder Singh
Tejinder Singh

Reputation: 1120

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder

I am working on Azure functions with Autofac container. I have implemented generic repository pattern in project to interact with backend.

I am not sure what I am doing wrong may be there is a problem while registering the Generic types.

If I remove generic repository part from my project it works fine.

I have visited all the links on stack overflow but didn't find any suitable solution.

I am facing the below error while running the function.

Executed 'sort' (Failed, Id=2cebaac1-a63e-4cf8-b82f-68e2ebeeb32d) [4/25/2019 12:28:18 PM] System.Private.CoreLib: Exception while executing function: sort. Microsoft.Azure.WebJobs.Host: Exception binding parameter '_chargeOptionsServcie'. Autofac: An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = ChargeOptionsService (ReflectionActivator), Services = [Awemedia.Chargestation.Business.Interfaces.IChargeOptionsServcie], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'Awemedia.Chargestation.Business.Services.ChargeOptionsService' can be invoked with the available services and parameters:

here is my function code:

[DependencyInjectionConfig(typeof(DIConfig))]
    public class Function1
    {
        [FunctionName("Function1")]
        public HttpResponseMessage Get(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequestMessage req, [Inject]IChargeOptionsServcie _chargeOptionsServcie, [Inject]IErrorHandler _errorHandler)
        {
            return req.CreateResponse(HttpStatusCode.OK, _chargeOptionsServcie.GetAll());
        }
    }

Here is my service code:

public class ChargeOptionsService : IChargeOptionsServcie
    {

        private readonly IBaseService<ChargeOptions> _baseService;
        private readonly IMapper _mapper;

        public ChargeOptionsService(IBaseService<ChargeOptions> baseService, IMapper mapper)
        {
            _baseService = baseService;
            _mapper = mapper;
        }


        public IEnumerable<ChargeOptionsResponse> GetAll()
        {
            return _baseService.GetAll().Select(t => _mapper.Map<ChargeOptions, ChargeOptionsResponse>(t));
        }

    }

here is my DIConfig.cs code where i am registering my dependencies:

public class DIConfig
    {
        public DIConfig(string functionName)
        {
            DependencyInjection.Initialize(builder =>
            {

                builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>));
                builder.RegisterGeneric(typeof(BaseService<>)).As(typeof(IBaseService<>));

                builder.RegisterType<ErrorHandler>().As<IErrorHandler>();
                builder.RegisterType<ChargeOptionsService>().As<IChargeOptionsServcie>();
                builder.RegisterType<EventsService>().As<IEventsService>();
            }, functionName);
        }
    }

My base service class:

public class BaseService<T> : IBaseService<T>
    {
        private readonly IBaseRepository<T> _repository;

        public BaseService(IBaseRepository<T> repository)
        {
            _repository = repository;
        }

        public IEnumerable<T> GetAll()
        {
            return _repository.GetAll();
        }

        public T GetById(int id)
        {
            return _repository.GetById(id);
        }

        public IEnumerable<T> Where(Expression<Func<T, bool>> exp)
        {
            return _repository.Where(exp);
        }

        public T AddOrUpdate(T entry, int Id)
        {
            var targetRecord = _repository.GetById(Id);
            var exists = targetRecord != null;

            if (exists)
            {
                _repository.Update(entry);
            }
            _repository.Insert(entry);
            return entry;
        }
        public T AddOrUpdate(T entry, Guid guid)
        {
            var targetRecord = _repository.GetById(guid);
            var exists = targetRecord != null;

            if (exists)
            {
                _repository.Update(entry);
            }
            _repository.Insert(entry);
            return entry;
        }
        public void Remove(int id)
        {
            var label = _repository.GetById(id);
            _repository.Delete(label);
        }

        public bool InsertBulk(IEnumerable<T> entities)
        {
            return _repository.InsertBulk(entities);
        }

        public T GetById(Guid guid)
        {
            return _repository.GetById(guid);
        }
    }

Here is my base repository :

public class BaseRepository<T> : IBaseRepository<T> where T : class
    {

        private readonly Context _context;

        private readonly DbSet<T> _entities;

        private readonly IErrorHandler _errorHandler;

        public BaseRepository(AwemediaContext context, IErrorHandler errorHandler)
        {
            _context = context;
            _entities = context.Set<T>();
            _errorHandler = errorHandler;
        }
        public IEnumerable<T> GetAll()
        {
            return _entities.ToList();
        }
        public T GetById(int id)
        {
            return _entities.Find(id);
        }

        public IEnumerable<T> Where(Expression<Func<T, bool>> exp)
        {
            return _entities.Where(exp);
        }
        public T Insert(T entity)
        {
            if (entity == null) throw new ArgumentNullException(string.Format(_errorHandler.GetMessage(ErrorMessagesEnum.EntityNull), "", "Input data is null"));
            _entities.AddAsync(entity);
            _context.SaveChanges();
            return entity;
        }
        public void Update(T entity)
        {
            if (entity == null) throw new ArgumentNullException(string.Format(_errorHandler.GetMessage(ErrorMessagesEnum.EntityNull), "", "Input data is null"));

            var oldEntity = _context.Find<T>(entity);
            _context.Entry(oldEntity).CurrentValues.SetValues(entity);
            _context.SaveChanges();
        }
        public void Delete(T entity)
        {
            if (entity == null) throw new ArgumentNullException(string.Format(_errorHandler.GetMessage(ErrorMessagesEnum.EntityNull), "", "Input data is null"));

            _entities.Remove(entity);
            _context.SaveChanges();
        }
        public bool InsertBulk(IEnumerable<T> entities)
        {
            bool result = false;
            if (entities.Count() > 0)
            {
                _entities.AddRange(entities);
                _context.SaveChanges();
                result = true;
            }
            return result;
        }
        public T GetById(Guid guid)
        {
            return _entities.Find(guid);
        }

    }

Please help me.I am breaking my head for last three days.

enter image description here

Upvotes: 1

Views: 1810

Answers (2)

Cyril Durand
Cyril Durand

Reputation: 16187

None of the constructors found with Autofac.Core.Activators.Reflection.DefaultConstructorFinder on type Awemedia.Chargestation.Business.Services.ChargeOptionsService can be invoked with the available services and parameters:

This error message means that Autofac can't create a ChargeOptionsService because one of the required dependency has not been registered. If you look at your ChargeOptionsService constructor, you can see that there is 2 dependencies :

public ChargeOptionsService(IBaseService<ChargeOptions> baseService, IMapper mapper)
{
    _baseService = baseService;
    _mapper = mapper;
}
  • IBaseService<ChargeOptions> baseService. This dependency is registered by the following line

    builder.RegisterGeneric(typeof(BaseService<>)).As(typeof(IBaseService<>));
    
    • IMapper mapper. This dependency is not registered.

To fix your error you should register a IMapper. Something like

builder.RegisterType<Mapper>().As<IMapper>();

can not resolve parameters AwemediaContext

This error message is almost the same, it means that one of your dependency needs a AwemediaContext is not registered.

Upvotes: 3

hannes neukermans
hannes neukermans

Reputation: 13367

did you try this:

// Register types that expose interfaces...
builder.RegisterType<BaseService<ChargeOptions>>.As(typeof(IBaseService<ChargeOptions>));

Otherwise change your ChargeOptionsService code. Give it a default constructor. see if that works, the re-add the constrcutor argument one by one, and see where it goes wrong.

Upvotes: 0

Related Questions