Having trouble getting the value of a ConstructorArgument parameter passed to kernel.Get(). I want to use the parameter's value to determine which of two string values will be passed into the constructor. The parameter is in fact there when expected, I just can't get at its value. I end up with a null ref exception after calling the parameter's GetValue method:
namespace MyNS.DBProviders {
public abstract class DBProviderBase {
private ObjectContext _db;
public DBProviderBase(ObjectContext db) {
_db = db;
}
...
//abstract methods here
...
}
public class DBProviderB : DBProviderBase {
public DBProviderB(ObjectContext db) : base(db) {}
//implementation details... applies to two DBs w/ same schema
}
public class DBProviderModule : NinjectModule {
public override void Load() {
//Bind DB providers
Bind<DBProviderBase>().To<DBProviderB>();
//Bind LINQ contexts to DB providers
Bind<ObjectContext>().To<EF_DB_b>()
.When(UseEF_DB_b_conn1).WithConstructorArgument(
"connectionString"
, ConfigurationManager.ConnectionStrings["EF_DB_b_conn1"]
.ToString()
)
;
Bind<ObjectContext>().To<EF_DB_b>()
.When(UseEF_DB_b_conn2).WithConstructorArgument(
"connectionString"
, ConfigurationManager.ConnectionStrings["EF_DB_b_conn2"]
.ToString()
)
;
}
public static bool UseEF_DB_b_conn1(IRequest req) {
string idNum = (string)req.Parameters.First(
p => p.Name == "idNum"
).GetValue(null, null);
//NULL REF EXCEPTION
return x != null ? idNum.Substring(0, 1) == "2" : false;
}
public static bool UseEF_DB_b_conn2(IRequest req) {
return !UseEF_DB_b_conn1(req);
}
}
}
namespace MyNS {
public static class DBProviderFactory {
public static DBProviderBase GetDBProvider(string idNum) {
var kernel = new Bootstrapper().Kernel;
return kernel.Get<DBProviderBase>(
new ConstructorArgument("idNum", idNum)
);
}
}
}
...//idNum received from elsewhere
var db = DBProviderFactory.GetDBProvider(idNum);
var something = db.GetSomethingFromOneOfThreeDBs();
return UseEF_DB_b_conn1() || UseEF_DB_b_conn2();
always returns true. So I'm not sure when you should use the binding forDBProviderB
. – Nesselrode