Draco
Draco

Reputation: 16364

Injecting repository instance into class

I've started designing parts of a fairly large system and was wondering what would be the best way to use repositories.

Which method would be better:

        static void Main(string[] args)
        {
            var dataRepository = new DataRepository();
            var classA = new ClassA(dataRepository);
            classA.Save();
        }

        public interface IDataRepository
        {
            void Save(ClassA myInstance);
        }

        public class DataRepository : IDataRepository
        {
            public void Save(ClassA myInstance)
            {
                //Do some stuff
            }
        }

        public class ClassA
        {
            private IDataRepository _dataRepository;
            public ClassA(IDataRepository dataRepository)
            {
                _dataRepository = dataRepository;
            }

            public void Save()
            {
                _dataRepository.Save(this);
            }
        }

Or should I do:

static void Main(string[] args)
{
    var dataRepository = new DataRepository();
    var classB = new ClassB();
    dataRepository.Save(classB);
}

public interface IDataRepository
{
    void Save(ClassB myInstance);
}

public class DataRepository : IDataRepository
{
    public void Save(ClassB myInstance)
    {
        //Do some stuff
    }
}

public class ClassB
{
    //some stuff    
}

Or is there any other way I could this more elegantly?

Upvotes: 0

Views: 404

Answers (1)

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64931

Actually your choices aren't worse or better, but they're different.

In my case, since DDD is friendly with my own way of structuring my mind, I go with #2. Usually this approach is better (it's my point of view) because it favors a better separation of concerns and less coupling: your POCO classes have no dependency with their repositories, while active record pattern has the drawback of turning your classes very specific for its use case (they're less reusable).

Or is there any other way I could this more elegantly?

This is a very broad question, I would need to write a book to give you a possible and exact answer to it.

BTW, I believe that you should take a look at unit of work pattern, which will empower your solution even more since you'll be able to implement tech-agnostic domain transactions.

Upvotes: 2

Related Questions