0

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 recommendation?

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
epaulk
  • 309
  • 1
  • 4
  • 15

2 Answers2

5

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.

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
0

I would rather take a repository "Generator" in a constructor. That would give you the same result, but with a correct injection.

Tengiz
  • 8,011
  • 30
  • 39
  • 2
    No, that would be a Leaky Abstraction. See e.g. http://stackoverflow.com/questions/4648318/dependency-injection-new-instance-required-in-several-of-a-classes-methods/4650050#4650050 for an similar question and an explanation for why it would be a leaky abstraction. – Mark Seemann Mar 13 '11 at 14:44
  • Personally I prefer classic dependency injection approach http://martinfowler.com/articles/injection.html – Tengiz Mar 15 '11 at 16:09