2012-04-15 43 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的基础构造函数类。