2016-11-04 9 views
1

Я пытаюсь внедрить инъекцию зависимостей с Autofac в проекте ASP.NET MVC5. Но я получаю следующую ошибку каждый раз, когда:Настройка Autofac с ASP.NET MVC 5

Ни один из конструкторов не найдено с «Autofac.Core.Activators.Reflection.DefaultConstructorFinder» на «типа MyProjectName.DAL.Repository` ........

код конфигурации

Мои Autofac в папке App_Start следующим образом:

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

Вот мой 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>(); 
     } 
..................... 
} 

Вот мой студент Контроллер:

public class StudentController : Controller 
    { 

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

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

Что случилось в моей Autofac Configuration..Any Помощь Пожалуйста??

+0

Что делает конструктор вашего контроллера класса выглядеть? Это зависит от типа интерфейса 'IRepository' или конкретного типа' Repository'? И как выглядит конструктор класса репозитория? Пожалуйста, напишите полный пример. –

+0

@IanMercer Вопрос редактируется .. Пожалуйста, смотрите сейчас. – TanvirArjel

+0

Где вы регистрируете «SchoolContext» с Autofac? Без этого (предположительно, как регистрация PerHttpRequest) он не может создать репозиторий. –

ответ

1

Чтобы ввести зависимость, вам необходимо выполнить все зависимости для всех частей цепи.

В вашем случае конструктор Repository не может быть удовлетворен без SchoolContext.

Так при регистрации добавить:

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

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

+0

Спасибо! Оно работает!! Хотя я нашел решение в статье проекта кода всего за несколько секунд, прежде чем видеть ваш ответ! :) Привет! – TanvirArjel