我有一个类LkCredentials,用于存储 SQL 表中的数据。
[Table(Name = "Credentials")]
public class LkCredentials : LkTable
{
// Database fields
[Column(Name = "id", IsPrimaryKey = true)]
public Binary Uid { get; set; }
...
// Used for dependency injection through Ninject
public ICustomer Customer { get; set; }
public LkCredentials(ICustomer Customer)
{
this.Customer = Customer;
}
// Data loader from database
public void Load(string login)
{
var user = (new SqlTRepository<LkCredentials>()).DBObject.Where(x => x.Login == login).Single();
... // copying data from user to this
}
我正在使用 Ninject 以这种方式注入正确的ICustomer类:
// Create new instance for correct constructor to run and Ninject to resolve
var cred = new LkCredentials((ICustomer)null);
// Load data from database
cred.Load(model.UserName);
但是在加载数据的过程void Load
中(如果我创建无参数构造函数,那么它将用于创建 LkCredentials 的新实例,但 Ninject 不会绑定正确的类 - 导致构造函数不正确 :( 并且会引发NullReference 异常。
我试图创建构造函数链:
public LkCredentials() : this((ICustomer)null)
{ }
但它没有用。我可以做些什么让 Ninject 正常工作?有任何想法吗?
PS:
Ninject 作为MVC Extension安装。控制器中的 Ninject 注入效果很好,具有相同的绑定。
来自NinjectWebCommon.cs的 Ninject 绑定:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<ICustomer>().ToProvider<ObjectProvider<ICustomer, Customer, Customer82>>();
kernel.Bind<IAddress>().ToProvider<ObjectProvider<IAddress, Address, ContactInfo>>();
}
public class ObjectProvider<T1,T2,T3> : IProvider
{
public Type Type { get { return typeof(T1); } }
public object Create(IContext context)
{
var securityInfo = context.Kernel.Get<SecurityInformation>();
if (securityInfo.isAuthenticated & securityInfo.DatabaseType == "81")
return context.Kernel.Get<T2>();
else if (securityInfo.isAuthenticated & securityInfo.DatabaseType == "82")
return context.Kernel.Get<T3>();
else
return context.Kernel.Get<T2>();
}
}