如何使用ninject替换存储库工厂

时间:2015-11-25 01:10:20

标签: c# ninject

我有一些我想要重构的代码看起来像这样:

public static class RepositoryFactory
{
    public static IRepository Create(RepositoryType repositoryType)
    {
        switch(repositoryType)
        {
            case RepositoryType.MsSql:
                return new MsSqlRepository();
                break;
            case RepositoryType.Postgres:
                return new PostgresRepository();
                break;
            //a lot more possible types
        }
    }
}

根据HTTP请求中的参数调用哪个:

public ActionResult MyAction()
{
    var repoType = RepositoryType.MsSql; //Actually determined from HTTP request, could be any type.
    var repository = RepositoryFactory.Create(repoType);
}

所以我真正想做的是重构,以便我的控制器看起来像这样:

[Inject]
public ActionResult MyAction(IRepository repository)

但是由于RepositoryType可能会在每个请求上发生变化,我无法弄清楚如何利用ninject的条件绑定来实现这一点。我知道如何使用条件绑定,例如Bind<IRepository>().ToMethod()Bind<IRepository>().To<MsSqlRepository>().WhenInjectInto()等,但是当绑定条件来自外部源时,我无法弄清楚该做什么。

1 个答案:

答案 0 :(得分:1)

这实际上应该很容易:

kernel.Bind<IRepository>().To<MsSqlRepository>()
      .When(ctx => System.Web.HttpContext.Current.... (condition here) );

kernel.Bind<IRepository>().To<PostgresRepository>()
      .When(ctx => System.Web.HttpContext.Current.... (condition here) );

您也可以将其定义为&#34;默认&#34;另一个是有条件的:

// this will be used when there's not another binding
// for IRepository with a matching When condition
kernel.Bind<IRepository>().To<MsSqlRepository>(); 

// this will be used when the When condition matches
kernel.Bind<IRepository>().To<PostgresRepository>()
      .When(ctx => System.Web.HttpContext.Current.... (condition here) );
相关问题