是否可以使用依赖注入将会话中的值传递给UnitOfWork构造函数?

时间:2013-09-17 02:21:55

标签: asp.net-mvc-4 dependency-injection ninject parameter-passing unit-of-work

我目前正在努力支持mvc4项目中的多租户。现在,我知道我必须在UnitOfWork构造函数中执行以下查询:

"USE FEDERATION <FederationName>(FederationKey=<FederationID>) WITH RESET, FILTERING=ON"

现在从会话中检索值(FederationName)和(FederationID),因此我必须将这些作为参数传递给UnitOfWork构造函数,但我想知道,这是否可以使用依赖注入?如果有,怎么样?我正在使用ninject作为依赖注入器。 这是绑定当前在NinjectWebCommon.cs中的完成方式:

private static void RegisterServices(IKernel kernel)
{
    ...
    kernel.Bind<IUnitOfWork>().To<UnitOfWork>();
    ...
}

这就是UnitOfWork构造函数的样子:

public UnitOfWork(DbContext dbContext, string federationName, int federationID)
{
    Database = dbContext;
    ((IObjectContextAdapter)dbContext).ObjectContext.Connection.Open();
    Database.Database.ExecuteSqlCommand(
        string.Format(@"USE FEDERATION {0}({1}={2}) WITH RESET, FILTERING={3}", 
        federationName,
        "FID",
        federationID,
        "ON"));
}

1 个答案:

答案 0 :(得分:0)

绑定WithConstructorArgument接口时,可以使用方法IUnitOfWork。这样,您可以将参数绑定到将在解析IUnitOfWork时执行的lambdas,从会话中检索federationName \ federationID。检查this question有关如何使用该方法的信息。

因此,在您的情况下,您可以将IUnitOfWork注册为:

kernel.Bind<IUnitOfWork>()
.To<UnitOfWork>()
.WithConstructorArgument("federationName", 
                          ctx => HttpContext.Current.Session["federationName"])
.WithConstructorArgument("federationID", 
                          ctx => HttpContext.Current.Session["federationID"]);

您可能想要考虑在会话中找不到这些值时会发生什么。另一件需要考虑的事情可能是将会话包装在您自己的上下文对象中(如果您计划在稍后阶段离开应用程序中的会话,则会很有趣)。然而,这应该让你开始。

希望它有所帮助!