处理应用程序的设置与ninject和惯例基结合 [英] Handling application settings with ninject and convention based binding

查看:141
本文介绍了处理应用程序的设置与ninject和惯例基结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是在MVC3应用程序中使用Ninject,我试图切换到基于与ninject.extensions.conventions约束力的公约。

现在让我们说我有一个需要访问应用程序设置,如类:

 公共类Foo:IFoo的
{
  公共美孚(字符串的connectionString)
  {...}
}

我想我明白该怎么做正常的约束力与Ninject是这样的:

 绑定<的IFoo>()
  。要<富>()
  .WithConstructorArgument(
    的connectionString
    。ConfigurationManager.ConnectionStrings [默认]的ConnectionString);

但是我怎么做到这一点使用约定呢?


如果需要额外的信息:

我使用的NuGet Ninject.MVC3封装和App_Start / NinjectWebCommon.cs的RegisterServices这是我目前有:

  kernel.Bind(X => X
                .FromAssembliesMatching(*)
                .SelectAllClasses()
                .BindDefaultInterface());


解决方案

Ninject的公约有没有让你90%的工作对成本的10%。如果你认为你需要添加额外的绑定在上面吧,别担心。

但在你的情况,我就不会担心没有注射通过构造连接字符串,只是手动抓取太多。或者,您可以设置基于绑定的IDatabaseConfig接口和实现,可以为你做,你的约定应该只是捡起权利了。我们做以后我们的项目

I am using Ninject in an MVC3 application and am trying to switch over to conventions based binding with ninject.extensions.conventions.

Now let's say I have a class that needs access to application settings such as:

public class Foo : IFoo
{
  public Foo(string connectionString)
  { ... }
}

I think I understand how to do normal binding with Ninject like this:

Bind<IFoo>()
  .To<Foo>()
  .WithConstructorArgument(
    "connectionString",
    ConfigurationManager.ConnectionStrings["Default"].ConnectionString);

But how do I do this using conventions instead?


Extra information if needed:

I'm using the nuget Ninject.MVC3 package and in App_Start/NinjectWebCommon.cs's RegisterServices this is all I currently have:

kernel.Bind(x => x
                .FromAssembliesMatching("*")
                .SelectAllClasses()
                .BindDefaultInterface());

解决方案

Ninject Conventions are there to get you 90% of the work for 10% of the cost. If you think you need to add an additional binding on top it, don't worry about it.

But in your scenario, I wouldn't worry too much about not injecting the connection string via the constructor and just grabbing it manually. Alternatively, you could setup an IDatabaseConfig interface and implementation that could do it for you, and your conventions based binding should just pick it right up. We do the later on our projects

这篇关于处理应用程序的设置与ninject和惯例基结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆