MVC3,Ninject和Ninject.MVC3问题

时间:2011-07-09 03:50:30

标签: asp.net-mvc-3 dependency-injection ninject

我刚开始使用Ninject和MVC3,所以这是我的问题: - 我从Nuget安装了Ninject 2.2.1.4和Ninject.MVC3 2.2.2.0 - 在我的WebUI(MVC3项目)中:

的Global.asax.cs

public class MvcApplication : NinjectHttpApplication
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "home", action = "index", id = UrlParameter.Optional } // Parameter defaults
        );

    }

    protected override void OnApplicationStarted()
    {
        base.OnApplicationStarted();

        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

    protected override IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Load(Assembly.GetExecutingAssembly());
        return kernel;
    }


}
  • 在我的域(类项目)中,我有我的LinQ to SQL datacontext,我想在我的WebUI中使用Web.Config中的连接字符串加载上下文,所以我必须传递构造函数参数,我的域项目中也有一些服务

    public class LotteryDataService
    {
        LinQ.WebDataContext _context;
    
        public LotteryDataService(LinQ.WebDataContext context)
        {
            _context = context;
        }
    
        public IEnumerable<LinQ.LotteryData> Get()
        {
            return _context.LotteryDatas.Take(10);
        }
    }
    

如何将datacontext与Ninject绑定到构造函数参数(这里是连接字符串)?

2 个答案:

答案 0 :(得分:3)

这是传递构造函数参数的方法。 Ninject将解析与指定的构造函数参数匹配的构造函数。

public class DataModule : NinjectModule
{
    public override void Load()
    {
        string connectionString = "...";
        Bind<WebDataContext>().ToSelf()
            .WithConstructorArgument("connection", connectionString);
    }
}

.WithConstructorArgument()的第一个参数应该是构造函数参数的名称。这是基类中的fileOrServerOrConnection,但是派生类中的connection

答案 1 :(得分:0)

下面的代码快照可能会有所帮助。希望它能提供更大的灵活性!

public class MvcModule : NinjectModule
{
    //Bind the default connection string
    public void BindDataContext()
    {
        ConstructorArgument parameter = new ConstructorArgument("connectionString", "[Config Value]");
        Bind<DataContext>().ToSelf().InRequestScope().WithParameter(parameter);
    }
    public override void Load()
    {
         BindDataContext();
         Bind(typeof(IRepository<>)).To(typeof(EntityRepository<>)).InRequestScope();
         ........
    }
    //Re-Bind the connection string (in case of multi-tenant architecture)
    public void ReBindDataContext(string cn)
    {
         ConstructorArgument parameter = new ConstructorArgument("connectionString", cn);
         Rebind<DataContext>().ToSelf().InRequestScope().WithParameter(parameter);
    }
    //Re-Bind the connection string (in case of multi-tenant architecture)
    public static void ReBindDataContext(IKernal kernel,string cn)
    {
         IEnumerable<INinjectModule> ml = kernel.GetModules();
         var myModule = ml.Where(i => i.Name.ToLowerInvariant().Contains("mvcmodule")).Select(i => i).Take(1);
         MvcModule mm = myModule.ToList()[0] as MvcModule ;
         mm.ReBindDataContext(cn);
    }
    //Return the module, for further modification like connection string
    public static MvcModule GetModule(IKernal kernel)
    {
        IEnumerable<INinjectModule> ml = kernel.GetModules();
        var myModule = ml.Where(i => i.Name.ToLowerInvariant().Contains("mvcmodule")).Select(i => i).Take(1);
        MvcModule mm = myModule.ToList()[0] as MvcModule ;
        return mm;
    }
}