cdaq
cdaq

Reputation: 167

DI: Associating entities with repository

I'm pretty new to the concept. What I'm trying to do is create a factory that will return an object that is used for repository functions. No problems there. So I create the instance of a concrete factory in main() and store it in a static property of App but my entities are in a separate dll. Does it make sense to pass the repository to each entity class in the constructor? This doesn't feel right. My question is: how is the best make my entities aware of which repository they should be using?

My App partial class looks like

public partial class App : Application
{
 private static ICalDataAccess _daqFactory;

 public static ICalDataAccess DataAccessFactory
 {
   set { _daqFactory = value; }
   get { return _daqFactory; }
 }
}

Maybe a little more code is in order.

public class Widget
{
    public string Description { get; set; }
    public int ID { get; set; }

    private IWidgetRepository _widgetRepository;
    public Widget(IWidgetRepository WidgetRepository)
    {
        _widgetRepository = WidgetRepository;
    }

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

Am I doing anything egregious here?

Upvotes: 3

Views: 252

Answers (2)

Morten Mertner
Morten Mertner

Reputation: 9474

I think the general recommendation is to keep your entities free from persistence concerns. That is, you have some code that retrieves the entities and uses them to perform whatever work needs to be done, resulting in new, deleted or modified entities, which the calling code then submits to the appropriate repository (or asks to be saved if you have something which tracks or detects modified entities, like EF or NHibernate).

That way your entities do not need to know about repositories at all.

I usually create a UnitOfWork helper class which exposes all of my repositories through a "public RepositoryFactory Repositories { get; }" property, so that simply by supplying an instance of the UnitOfWork class I have access to all of my data sources. UnitOfWork can then be injected via IoC to whatever class needs to have data access.

Some recommended reading on this topic:

Upvotes: 3

Jim Bolla
Jim Bolla

Reputation: 8295

Your description sounds more like the service locator pattern than dependency injection. Dependency injection typically looks like any object that needs some service object (such as data access) to do its work receives that service as parameter to its constructor.

Upvotes: 0

Related Questions