Search code examples
c#ninject

Should i use ninject to initialize service with repository?


I have class which have :

IMessageRepository messageRepository;
IMessageService messageService;

Should i put both of them in constructor of the class and because of that use ninject to initialize both of them ?

public MessageController(IMessageRepository messageRepository, IMessageService messageService)
    {
        this.messageRepository = messageRepository;
        this.messageService = messageService;
    }

Or should i take only messageRepository from ninject and initialize my messageService with it? (It takes IMessageRepository in constructor)

public MessageController(IMessageRepository messageRepository)
    {
        this.messageRepository = messageRepository;
        this.messageService = new MessageService(messageRepository);
    }

Solution

  • I would prefer to put both of them in constructor parameters.

    Because, in future, you might have another realization of IMessageRepository.

    Moreover, you will have more control over your dependencies outside of your classes (e.g. you might need to use different repositories in Controller and Service).

    Hope it will help.