Question

The title really says it all. I have some Action methods that don't use the repository at all, like this Index() method that just displays a static page.

public ActionResult Index()
{
    return View();
}

Seems to me like instantiating the Repository in the controller is a waste of time in these cases... but for IoC, I want to hand in an interface, so that has to happen in the controller:

public PerfMvcController(IPerfRepository repo)
{
    repo = repo ?? new PerfRepository();
}

I would be interested in the best practice for instantiating a repository in a controller using IoC, in a nutshell.

Était-ce utile?

La solution

Whats more wasteful?

  1. Duplicating your code all over the place, or
  2. Single line initialization (DRY principle)

The reason why it is a general accepted to inject the repository in the constructor is because it makes the dependencies clear, (they are at one place and one place only)

Dependencies are clear by just checking the constructor, instead of buried deep in the implementations. You may not notice this in the early stages because you only have basic functions (CRUD), but as your application grows you will start noticing the advantage of not having to hunt down dependencies.

If you are worried about performance, most ORM (if you are using one) has lazy initialization.

Another common practice is to instantiate repositories somewhere else (IoC container), then injected in the controller's constructor.

Off Topic

repo = repo ?? new PerfRepository();

Constructing your own concrete repository within your controller increases coupling, therefore breaks the IoC pattern. Instead, you should throw an exception whenever null, plus it supports fail-fast technique (a technique for building high-quality application)

Autres conseils

I think you're a lot better off having your IPerfRepository injected in via the controller's constructor, as opposed to duplicating code in your actions.

If you're worried about the repository's constructor being heavy, and executing it regardless of whether you use the repository, you could look at using an IoC container that supports injecting Lazy<T>.

Autofac is a good example of this: for any service registered with Autofac, such as your IPerfRepository, you can ask for a Lazy<IPerfRepository> instead. That way, you won't even instantiate a new repository unless you access the injected object's .Value property.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top