Ninject + ASP.NET MVC + InRequestScope [英] Ninject + ASP.NET MVC + InRequestScope

查看:210
本文介绍了Ninject + ASP.NET MVC + InRequestScope的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与Ninject有问题。

I have a problem with the 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。但我的解决方案不工作。我究竟做错了什么? =(

I want that each user request to my asp.net mvc site creates a single SQLServer, a single ISQLLogger and a single DatabaseConnections. But my solution dont work. What am I doing wrong? =(

推荐答案

您不需要指定 WithConstructorArgument 。解决这些参数你注入对象的构造是什么样Ninject为你做的一部分。所以定义应该看起来更像是这样的:

You don't need to specify the WithConstructorArgument. Resolving the parameters to the constructors of your injected objects is part of what Ninject does for you. So the definitions should look more like this:

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();

这篇关于Ninject + ASP.NET MVC + InRequestScope的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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