Home > Net >  Specify what implementation should be injected to class
Specify what implementation should be injected to class

Time:04-01

I have an interfaces : IBook and IMovie. IBook is implemented by class Book, this class have object of IMovie. IMovie is implemented by two classes : Movie1, Movie2

public class Book: IBook
{
   private IMovie _movie;
   public Book(IMovie movie) _movie = movie
}

In every case I want to inject Movie1 implementation to IBook, except one situation. In one class that have object of Book I want to inject Movie2 to Book. Is it possible to specify such a case ? Or maybe I shouldnt use DI in this case and create objects manually ?

CodePudding user response:

2 Ideas -

1 - You could have 2 interfaces/classes that inherit from IMovie/Movie of IMovie1 and IMovie2, register both and inject the relevant one.

2 - Create an IMovieFactory that has a method that takes some parameter to select the correct implementation and return the relevant implementation.

  •  Tags:  
  • c#
  • Related