Ninject + ASP.NET MVC + InRequestScope

时间:2010-12-20 18:57:53

标签: asp.net-mvc ninject

我对Ninject有疑问。

我的约束规则:

this.Bind<ISphinxQLServer>().To<SQLServer>();
this.Bind<IMySQLServer>().To<SQLServer>();

this.Bind<ISQLLogger>().To<StandardSQLLogger>()
    .InRequestScope();

this.Bind<DatabaseConnections>()
    .ToMethod(x => ConnectionFactory.GetConnections())
    .InRequestScope();

this.Bind<SQLServer>().ToSelf()
    .InRequestScope()
    .WithConstructorArgument("connections", Kernel.Get<DatabaseConnections>())
    .WithConstructorArgument("logger", Kernel.Get<ISQLLogger>());

其中

SQLServer,ISphinxQLServer和IMySQLServer是:

public class SQLServer: ISphinxQLServer, IMySQLServer
{
    public DatabaseConnections Connections { get; internal set; }
    public ISQLLogger Logger { get; internal set; }

    public SQLServer(DatabaseConnections connections)
    {
        this.Connections = connections;
    }

    public SQLServer(DatabaseConnections connections, ISQLLogger logger)
    {
        this.Connections = connections;
        this.Logger = logger;
    }
}

我希望每个用户对我的asp.net mvc网站的请求都会创建一个SQLServer,一个ISQLLogger和一个DatabaseConnections。但我的解决方案不起作用。我究竟做错了什么? =(

1 个答案:

答案 0 :(得分:6)

您无需指定WithConstructorArgument。解析注入对象的构造函数的参数是Ninject为您做的一部分。所以定义看起来应该更像这样:

this.Bind<SQLServer>()
    .ToSelf()
    .InRequestScope();

this.Bind<ISphinxQLServer>()
    .ToMethod( x => x.Kernel.Get<SQLServer>() );

this.Bind<IMySQLServer>()
    .ToMethod( x => x.Kernel.Get<SQLServer>() );

this.Bind<ISQLLogger>()
    .To<StandardSQLLogger>()
    .InRequestScope();

this.Bind<DatabaseConnections>()
    .ToMethod(x => ConnectionFactory.GetConnections())
    .InRequestScope();