2016-11-04 92 views
1

我想在ASP.NET MVC5项目中使用Autofac实现依赖注入。但我每次都收到以下错误:使用ASP.NET MVC配置Autofac 5

建设者没有发现与类型“Autofac.Core.Activators.Reflection.DefaultConstructorFinder“MyProjectName.DAL.Repository` ........

在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 Configuration..Any帮助请??

+0

什么是你的控制器类样子的构造?它取决于接口类型“IRepository”还是具体类型“Repository”?那么存储库类的构造函数是什么样的?请发布完整的示例。 –

+0

@IanMercer问题已被编辑..请看现在.. – TanvirArjel

+0

你在Autofac注册'SchoolContext'在哪里?如果没有(大概作为'PerHttpRequest'注册)它不能创建存储库。 –

回答

1

要注入依赖关系,您需要满足链中所有片断的所有依赖关系。

就你而言,如果没有SchoolContext,构造函数Repository就不能满足。

所以在您的注册地址:

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

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

+0

谢谢!有用!!尽管我在查看答案之前几秒钟就在代码项目文章中找到了解决方案! :)干杯! – TanvirArjel