I using Ninject 3 in Repository pattern in mvc 3 (steven sanderson Scaffolder).
and in ninject i have the class "NinjectWebCommon" which in the "RegisterServices" method i resolved the dependencies and i think im ready to go.
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<ICityRepository>().To<CityRepository>();
kernel.Bind<IVillageRepository >().To<VillageRepository>();
}
i using my repositories in controllers using constructor injection and everything is fine.
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;
}
// .........
}
but when i use this repositories in other classes like Model(Entity) classes using property injection or field injection the dependency doesn't resolved and i get null reference exception on my Property or field.
[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; }
}
i don't know why this happening. so whats the problem and how can i use the repositories in non-controller classes?
thanks in advance.
new
s in the IL with magic interception (you may know that, but please edit the question to make stuff like this clear) – Ruben BartelinkIVillageRepository villageRepo=new VillageRepository();
i will break the whole pattern right? all i want is to use Repository classes not just in Controller classes through Constructor Injection because its obvious that i won't be needed to work with database just in my Controllers. so how? sorry for weak English. – Jalali ShakibFunc<T>
methods. I'd also recommend manning.com/seemann as an excellent investment for understanding the best approaches around this top to bottom. Your next step while the book is on the way is to go reading Mark Seemann's top answers on SO, and some others re injecting Entities. – Ruben Bartelink