mashta gidi
mashta gidi

Reputation: 867

c# mvc DI ninject repository

I am working with .net c# Mvc, using ninject repository pattern. My problem is that when developing I am using reusing in the functions, and everytime I want more info from db and need access to another table, I need to pass the repositories from all the places that are calling this function. Am I doing it wrong? ot this is the way, which is alot longer to develop then just opening a connection and disposing at the end of the function.

Upvotes: 0

Views: 194

Answers (2)

user10038293
user10038293

Reputation:

use a unit of work the new up all of the repositories. That way you can pass in the uow into your controllers and have access to all repos when needed.

Upvotes: 0

Neil Thompson
Neil Thompson

Reputation: 6425

If your class needs to have loads of repositories passed in this can sometimes be a sign that your class is doing too many things and probably breaking the Single Responsibility Principle. Perhaps if you broke this class into smaller more specialized classes the problem would not be so bad.

On the other hand, sometimes passing in loads of repositories is unavoidable. You might consider making a factory class that creates the class suffering from 'constructor jam' for you - this should save some typing as the hefty constructor initialization is just in one place (in the factory class).

edit: A really simple 'factory' class might be as follows:

    public class FactoryClass
    {        
        public ClassWithLotsOfRepositories GetClassWithLotsOfRepositories()
        {
            return new ClassWithLotsOfRepositories(new repository1(), 
                          new repository2(), new repository3() );
        }
    }

So you can now create an instance of ClassWithLotsOfRepositories without having to specify the repositories in the constructor each time.

ClassWithLotsOfRepositories myClassThatUsesLotsOfRepositories = new FactoryClass().GetClassWithLotsOfRepositories();

My example has concrete classes passed in through the constructor. You are using Ninject so presumably have interfaces that need resolving - I'm just keeping this example simple to illustrate the concept.

Upvotes: 2

Related Questions