Andrew Savinykh
Andrew Savinykh

Reputation: 26300

How to inject a repository in a controller when repository is not known at controller construction time?

I have an application, where I do not know the full list of repositories a controller might need upfront (at the time the controller is constructed). A controller gets a list of "components" to render from the database, and then which additional repositories are needed depends on what "components" the database returns. Is there a way to inject these repositories? I'm using ninject although it probably does not matter.

Upvotes: 2

Views: 291

Answers (2)

Andrew Savinykh
Andrew Savinykh

Reputation: 26300

At the time I wrote my question, my "components" were implemented as partial views, and I rendered them from a view executed (Html.Partial) from a controller action. Thanks to this question and answer I changes this model, so that each of my "components" has it's own controller and instead of rendering partial view directly, actions marked with ChildActionOnly on these controllers are called from the view (Html.Action). This is done similar to what is described in the article linked in the original answer, although in my case the view engine was razor.

This way the whole problem does not exist any more - each component controller knows about its repositories now.

Upvotes: 0

shenku
shenku

Reputation: 12458

Make your repositories a dependency within your component. Most IOC software like Ninject will inject all the required dependancies for an object when you resolve it.

For example:

public class ComponentA : IComponent
{
    public IRepository RepositoryA {get;set;}
}

public class ComponentB : IComponent
{
    public IRepository RepositoryAnother {get;set;}
}

Whenever you load ComponentA or B its dependencies (in this case a IRepository) should get loaded as well.

So you don't need to know what Repository is required.

Upvotes: 1

Related Questions