Configuring Autofac with ASP.NET MVC 5

TanvirArjel picture TanvirArjel · Nov 4, 2016 · Viewed 12.2k times · Source

I am trying to implement Dependency Injection with Autofac in an ASP.NET MVC5 Project. But I am getting the following error every time:

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MyProjectName.DAL.Repository` ........

My Autofac configuration code in App_Start folder as follows:

public static class IocConfigurator
    {
        public static void ConfigureDependencyInjection()
        {
            var builder = new ContainerBuilder();

            builder.RegisterControllers(typeof(MvcApplication).Assembly);
            builder.RegisterType<Repository<Student>>().As<IRepository<Student>>();

            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }      
    }

In Global.asax file:

public class MvcApplication : HttpApplication
    {
        protected void Application_Start()
        {
            // Other MVC setup

            IocConfigurator.ConfigureDependencyInjection();
        }
    }

Here is my IRepository:

public interface IRepository<TEntity> where TEntity: class 
    { 
        IQueryable<TEntity> GelAllEntities();
        TEntity GetById(object id);
        void InsertEntity(TEntity entity);
        void UpdateEntity(TEntity entity);
        void DeleteEntity(object id);
        void Save();
        void Dispose();
    }

Here is my Repository:

public class Repository<TEntity> : IRepository<TEntity>, IDisposable where TEntity : class
    {
        internal SchoolContext context;
        internal DbSet<TEntity> dbSet;

        public Repository(SchoolContext dbContext)
        {
            context = dbContext;
            dbSet = context.Set<TEntity>();
        }
.....................
}

Here is my Student Controller:

public class StudentController : Controller
    {

        private readonly IRepository<Student> _studentRepository;
        public StudentController()
        {

        }
        public StudentController(IRepository<Student> studentRepository)
        {
            this._studentRepository = studentRepository;
        }
       ....................
}

What's wrong in my Autofac Configuration..Any Help Please??

Answer

Ian Mercer picture Ian Mercer · Nov 4, 2016

To inject a dependency you need to have satisfied all of the dependencies for all of the pieces down the chain.

In your case, the Repository constructor cannot be satisfied without a SchoolContext.

So in your registration add:

  builder.RegisterType<SchoolContext>().InstancePerRequest();

See http://docs.autofac.org/en/latest/lifetime/instance-scope.html#instance-per-request