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