【问题标题】:Ninject + ASP.NET MVC + InRequestScopeNinject + ASP.NET MVC + InRequestScope
【发布时间】:2011-05-28 10:19:44
【问题描述】:

我的 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。但我的解决方案不起作用。我究竟做错了什么? =(

【问题讨论】:

    标签: asp.net-mvc ninject


    【解决方案1】:

    您无需指定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();
    

    【讨论】:

    • 谢谢,这帮助我解决了类似的问题。
    猜你喜欢
    • 1970-01-01
    • 2020-02-21
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 2011-05-20
    相关资源
    最近更新 更多