简体   繁体   中英

C# Inheritence: Choosing what repository based on type of inherited class

I have been making a program that downloads information about movies from the internet. I have a base class Title , which represents all titles. Movie , Serie and Episode are inherited from that class.

To save them to the database I have 2 services, MovieService and SerieService . They in turn call repositories, but that is not important here.

I have a method Save(Title title) which I am not very happy with. I check for what type the title is and then call the correct service. I would like to perhaps write like this:

ITitleService service = title.GetService();
title.GetSavedBy(service);

So I have an abstract method on Title that returns an ITitleSaver , which will return the correct service for the instance. To do this the services would have to implement ITitleSaver

My question is how should I implement ITitleSaver ? If I make it accept Title I will have to cast it to the correct type before calling the correct overload. Which will lead to having to deal with casting once again.

What is the best approach to dealing with this? I would like to have the saving logic in the corresponding class.

I don't understand the purpose of GetService. You only call that method to pass its result to GetSavedBy method? Here is my proposal:

  1. Expose an abstract Saver property on the Title class
  2. Define a concrete method Save on the Title class whose implementation is:

    this.GetSavedBy(Saver);

  3. In each Concrete class either create the required saver or use some dependency injection tool to inject the correct Saver at runtime.

Voila! this solves your problem neatly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM