7

我正在尝试在 ASP.NET MVC5 项目中使用 Autofac 实现依赖注入。但我每次都收到以下错误:

在“MyProjectName.DAL.Repository”类型上找不到使用“Autofac.Core.Activators.Reflection.DefaultConstructorFinder”的构造函数......

我在 App_Start 文件夹中的 Autofac 配置代码如下:

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

在 Global.asax 文件中:

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

            IocConfigurator.ConfigureDependencyInjection();
        }
    }

这是我的 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();
    }

这是我的存储库:

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

这是我的学生控制器:

public class StudentController : Controller
    {

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

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

我的 Autofac 配置有什么问题..请帮忙?

4

1 回答 1

11

要注入依赖项,您需要满足链下所有部分的所有依赖项。

在您的情况下,Repository没有SchoolContext.

因此,在您的注册中添加:

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

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

于 2016-11-04T12:59:07.447 回答