Ninject + ASP.NET MVC + InRequestScope

假如想象 提交于 2019-12-21 04:43:30

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/4492858/ninject-asp-net-mvc-inrequestscope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!