【发布时间】:2012-04-12 16:30:02
【问题描述】:
我正在尝试使用 Ninject 将存储库绑定到属性,但总是得到绑定对象的空引用。我将使用下面的代码解释问题。
public interface IServiceRepository
{
User GetUser(string email);
IQueryable<Statistic> GetStatisticForCurrentMonth(string ip);
void InsertStatistic(ConversionModel conversionModel);
class ServiceRepository : IServiceRepository
{
//Implementation of the Interface
}
我想在创建课程时将bind the repository above 发送到class below。不幸的是 Repository 对象始终是 null。也许我误解了 Ninject 的工作原理?如何解决问题?
public class Converter
{
[Inject]
public static IServiceRepository Repository { get; set; }
private static Converter _converter;
public static Converter Instance
{
get { return _Converter ?? (_Converter = new Converter ());
}
}
Ninject 激活码
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IServiceRepository>().ToMethod(context => Converter.Repository);
}
更新
我尝试过这样重写代码
public class Converter
{
private readonly IServiceRepository _repository;
public Converter(IServiceRepository repository)
{
_repository = repository;
}
//skip code
}
测试...
[TestMethod]
public void ConverterInstanceCreated()
{
using (IKernel kernel = new StandardKernel())
{
kernel.Bind<IServiceRepository>().To<ServiceRepository>();
Assert.IsNotNull(kernel.Get<Converter>());
}
}
给出异常
Test method PC.Tests.NinjectTest.ConverterInstanceCreated threw exception:
Ninject.ActivationException: Error activating IServiceRepository
No matching bindings are available, and the type is not self-bindable.
Activation path:
2) Injection of dependency IServiceRepository into parameter repository of constructor of type Converter
1) Request for Converter
我刚刚迷路了,我试图了解 Ninject 是如何工作了大约一周但没有任何成功。就我而言,为什么会引发此异常?
还请有人将一个存储库注入的工作示例发布到单例类。
【问题讨论】: