mvc 3(steven sanderson Scaffolder)のリポジトリパターンでNinject3を使用しています。
ninjectには、「RegisterServices」メソッドで依存関係を解決したクラス「NinjectWebCommon」があり、準備ができていると思います。
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<ICityRepository>().To<CityRepository>();
kernel.Bind<IVillageRepository >().To<VillageRepository>();
}
コンストラクターインジェクションを使用してコントローラーでリポジトリーを使用していますが、すべて問題ありません。
public class CityController : Controller
{
private readonly ICityRepository cityRepository;
// If you are using Dependency Injection, you can delete the following constructor
//public CityController() : this(new CityRepository())
//{
//}
public CityController(ICityRepository cityRepository)
{
this.cityRepository = cityRepository;
}
// .........
}
しかし、プロパティインジェクションやフィールドインジェクションを使用するModel(Entity)クラスなどの他のクラスでこのリポジトリを使用すると、依存関係が解決されず、プロパティまたはフィールドでnull参照例外が発生します。
[MetadataType(typeof(CityMetadata))]
public partial class City : IValidatableObject
{
[Inject]
public IVillageRepository VillageRepo { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var village = VillageRepo.Find(5); // will throw null reference exception on "VillageRepo"
}
}
public partial class CityMetadata
{
[ScaffoldColumn(false)]
public int ID { get; set; }
[Required(ErrorMessage = MetadataErrorMessages.Required)]
[StringLength(50, ErrorMessage = MetadataErrorMessages.ExceedMaxLength)]
public string Name { get; set; }
}
なぜこれが起こっているのか分かりません。では、問題は何ですか?コントローラー以外のクラスでリポジトリを使用するにはどうすればよいですか?
前もって感謝します。