1

I am currently using EntityFrameworkCore 2.0.0.

The application I am creating is an online store product scraper. All stores are saved in the database, and each store has a scraper that implements IStoreScraper.

This is my store model:

public class Store 
{
    public int Id { get; set; }
    public string Name { get; set; }

    [NotMapped]
    public IStoreScraper StoreScraper { get; set; }
}

I was wondering if it is possible to add the correct IStoreScraper object to the Store object when it is fetched from the database. Either by a value from the database or something else.

I also looked into injecting this in the constructor of the model, however, this violates the Dependency Injection pattern because each class has its own, already known, implementation.

Maybe I should even look at it from another perspective because this code should not be in a model class? Any ideas?

Jerodev
  • 32,252
  • 11
  • 87
  • 108

1 Answers1

0

You can override the object materialized event and add it here, as mentioned in this answer;

How to Inject Helper Dependencies in Domain Model Entity Classes

However I would highly recommend against this. EF is meant to be your data model, you should have a business layer above this, which is the correct place to add dependencies like this.

Milney
  • 6,253
  • 2
  • 19
  • 33
  • Okay, say that I make a `StoreFacade` class that I give the store object to and this handles the communication with the various scrapers, how would be the best way to get the correct scraper for each class? – Jerodev Aug 17 '17 at 13:32
  • Well that depends entirely on your requirements, kind of too broad for us to answer... You mentioned this may depend on a value stored in the database, is it stored against the entity itself? In this case you would simply look up the relevant scraper, from maybe a Dictionary passing in the value from the database, or whichever other way and assign it... Again I would recommend against this and instead preferring a Business Layer ontop of your EF models, but this approach should work fine... – Milney Aug 17 '17 at 13:48
  • 1
    Do you actually need to store the IStoreScaper against the entity?? It seems this should be passed in as an argument to whatever method performs the scraping (or ideally as a dependency to the service which performs the scraping)... i.e. at any rate - a higher level than the store domain object. I would seriously consider re-thinking your design – Milney Aug 17 '17 at 13:50