Tell me how to implement property injection in asp.net mvc as follows:
In all examples, injection injection is mainly shown through dependency injection through the controller. In my task, dependency injection must be implemented not in the controller but in a regular class, the point is that I wanted to implement a certain context class that will contain properties for all repositories in the application. And then use an instance of this class in the controller.
In my case, I created such a class, but when I first access the class property (which has this type for example: IRepository), I get an error at the execution stage that this property is null, that is, it is not initialized. How correctly can you implement such a class, please tell me, otherwise I don’t understand much in DI? Some code. For example, I need this class:
public class UoWManager { [Inject] public IRepository<Car> GetCarsrepository { get; set; } }
Then I create a wrapper (resolver):
public class NinjectDependencyResolver:IDependencyResolver { private IKernel kernel; public NinjectDependencyResolver() { kernel = new StandardKernel(); AddBindings(); } public object GetService(Type serviceType) { return kernel.TryGet(serviceType); } public IEnumerable<object> GetServices(Type serviceType) { return kernel.GetAll(serviceType); } private void AddBindings() { kernel.Bind<IRepository<Car>>().To<SQLCarsRepository>(); kernel.Bind<UoWManager>().ToSelf(); }
I register it in Global.asax:
DependencyResolver.SetResolver(new NinjectDependencyResolver());
And then I use my class - the context in the controller:
public class HomeController : Controller { public ActionResult Index() { UoWManager man=new UoWManager(); Car Temp = new Car(); Temp.Mark_car = "1"; Temp.Model_car = "2"; Temp.Price_car = 233234; Temp.Type_car = "Truck"; Temp.Year_of_issue_car = DateTime.Now.Year; man.GetCarsrepository.Create(Temp); return View(); } }
Here, in this situation, my GetCarsRepository
property GetCarsRepository
not initialized. And if, for example, to declare it right in the controller, then everything is in order.
Actually the question is - how to properly connect my UoWManager class with the project object?