Dependency Injection with repository "Generator"
I did my research and I can’t find any specific example of what I want to do.
I successfully implement Ninject into me MVC project. Everything works perfect. However, I want to do a last step.
Until now, I have been working like this (normal DI pattern):
public class myController : Controller
{
private iMyInterface myRepository;
public myController(iMyInterface myRepository)
{
this.myRepository = myRepository;
}
public ActionResult list(){
return view(myRepository.getMyList())
}
// rest o the code ...
}
My Question is; there is a way to do something like this? (Repository “Generator”)
public class myController : Controller
{
private iMyInterface myRepository = specialClass.GetMyRepository();
public ActionResult list(){
return view(myRepository.getMyList()) }
// rest o the code ...
}
I aware I’m writing a nonsense code, but the idea is to be able to do something similar.
Any recommen开发者_开发技巧dation?
I don't know what specialClass
is supposed to be, but this looks a lot like the Service Locator anti-pattern in action.
The first option where the repository is injected through the constructor is better, because it gives you more options, including using specialClass
:
var controller = new myController(specialClass.GetMyRepository());
I don't know Ninject, but most DI Containers give you an option to map an interface to a method call that returns an instance of the interface.
I would rather take a repository "Generator" in a constructor. That would give you the same result, but with a correct injection.
精彩评论