2016-11-04 63 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