我有一個類LkCredentials,它用於存儲來自SQL表的數據。處理Ninject綁定和無參數構造函數
[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,並且編譯器要求定義無參數的構造函數。如果我創建參數構造函數,那麼它將被用來創建LkCredentials的新實例,但Ninject不會綁定正確的類 - 事業構造不正確:(而且NullReference例外將提高
我試圖創建構造函數鏈:
public LkCredentials() : this((ICustomer)null)
{ }
但它沒有工作 我能做些什麼爲Ninject正常工作的任何想法
PS:??
Ninject安裝爲MVC分機。 控制器中的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>();
}
}
Ninject不會接管'new' - 在上面的代碼中,您每次都基本上傳遞一個空'ICustomer'。你嘗試過使用'kernel.Get()'而不是?另外,爲什麼不將'SqlTRepository '注入你的'LkCredentials'實例? –
@StephenByrne我不明白,我應該在哪裏使用'kernel.Get()'? –
Vasilij
'//正確構造運行和Ninject創建新實例解決 VAR名氣=新LkCredentials((ICustomer)NULL);' - 也許我看錯,但我明白這意味着你希望Ninject攔截這個'新'這裏的操作員。它不會。在這裏,您將需要使用'kernel.Get()'(當然你需要設置Ninject內核注入LKCredentials'的'實例) –