0

I have one abstract Class and tow implementation for it.

public abstract class Person{
    public abstract string GetName();
} 

public class Doctor : Person{
    public override string GetName()
    {
        return "Doctor";
    }
}

public class Teacher : Person{
    public override string GetName()
    {
        return "teacher";
    }
}

I am using unity to dependency injection.In unity I register Doctor and in run time I need to use teacher ,actually replace that injection in my test2 method : here is my unity injection :

container.RegisterType<Person, Doctor>();

here is my class constructor :

private readonly Iperson _person;
pubice myclass(Iperson person)
{
    _person=person
}

public voide test1()
{
    var Name=_person.GetName();
    // Name is : Doctor
}

public void test2()
{
    //????
    var Name=_person.GetName();
    // Name must be teacher 
}
George Alexandria
  • 2,841
  • 2
  • 16
  • 24
user3698913
  • 33
  • 1
  • 7
  • I'm not very familiar with unity, but you should probably inject them with name. In the runtime you could specify which one exactly you want, and if you want both, then register both. Look here: https://stackoverflow.com/questions/7046779/with-unity-how-do-i-inject-a-named-dependency-into-a-constructor – FCin Jun 25 '17 at 07:42

1 Answers1

0

I suggest you to register both of your derived classes: Doctor and Teacher

container.RegisterType<Person, Doctor>(nameof(Doctor));
container.RegisterType<Person, Teacher>(nameof(Teacher));

Pass IUnityContainer to MyClass and resolve in runtime what you want by name:

private readonly IUnityContainer _container;

public MyClass(IUnityContainer container)
{
    _container = container
}

public void test1()
{
    var name = container.Resolve<Person>(nameof(Doctor)).GetName();
    // Name is : Doctor
}

public void test2()
{
    var name = container.Resolve<Person>(nameof(Teacher)).GetName();
    // Name is : Teacher
}
George Alexandria
  • 2,841
  • 2
  • 16
  • 24