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 に答える