2012-04-15 22 views
1

我試圖從使用的NuGet包EntityFramework.Patterns,但我卡住了,這裏是我的如何在MVC 3中使用EntityFramework.patterns與ninject?

問題:如何使用ninject到MVC控制器內注入productRepo和的UnitOfWork?

這裏的教程鏈接:http://efpatterns.codeplex.com/wikipage?title=Pattern%20%3a%20Use%20Repository%20and%20UOF

DbContextAdapter adapter = new DbContextAdapter(ctx); 
IRepository<Product> productRepo = new Repository<Product>(adp); 
IUnitOfWork unitOfWork = new UnitOfWork(adp); 

回答

0

添加一個構造函數把他們作爲參數傳遞給控制器​​。搜索構造函數注入以獲取更多詳細信息。

+0

好吧,我解決了它 – dfang 2012-04-17 13:44:52

0
  • 從nuget下載Ninject.MVC3包。
  • 從AppStart的文件夾中刪除「ninject網上常見的」一塊
  • 打開你的Global.asax和改變你的代碼看起來像到以下

namespace OnBoardingMVC 
{ 
    public class MvcApplication : Ninject.Web.Common.NinjectHttpApplication 
    { 
     protected override IKernel CreateKernel() 
     { 
      var kernel = new StandardKernel(); 
      NinjectConfig.RegisterServices(kernel); 
      return kernel; 
     }  
     protected override void OnApplicationStarted() 
     { 
      base.OnApplicationStarted(); 
      AreaRegistration.RegisterAllAreas(); 
      WebApiConfig.Register(GlobalConfiguration.Configuration); 
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
      RouteConfig.RegisterRoutes(RouteTable.Routes); 
      BundleConfig.RegisterBundles(BundleTable.Bundles); 
     } 
    } 
} 

然後你就可以創建一個在您的App_Start文件夾中添加新的NinjectConfig.cs文件,並將以下代碼添加到您的課程中:

namespace OnBoardingMVC 
{ 
    public class NinjectConfig 
    { 
     public static void RegisterServices(IKernel kernel) 
     { 
      // e.g. kernel.Load(Assembly.GetExecutingAssembly()); 
      kernel.Bind(typeof(IEmployeeUow)) 
        .To(typeof(EmployeeUow)) 
        .WithConstructorArgument("adapter", <Add new AdapterVariable here>) 
      ; 
     } 
    } 
} 

然後,您可以創建一個EmployeeUow類,該類繼承UnitOfWork類,並創建一個從IUnitOfWork繼承的IEmployeeUow,並且上下文適配器將作爲構造函數的參數,並且構造器也將該適配器傳遞給UnitOfWork的基礎構造函數類。

相關問題