Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ninject + ASP.NET MVC + InRequestScope

I have a problem with the Ninject.

My binding rules:

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

Where

SQLServer, ISphinxQLServer and IMySQLServer are:

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;
    }
}

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? =(

like image 411
Jean Louis Avatar asked Dec 20 '10 18:12

Jean Louis


1 Answers

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();
like image 60
Paul Alexander Avatar answered Nov 03 '22 18:11

Paul Alexander