1

I only know how to Register and Resolve new instances. However, I am not sure how to pass existing objects as parameters in to an instance I want to resolve.

Q1:

interface IPerson {
  person FindAnOtherPerson();
  void MakeFriends();
}
class Person : IPerson {
  private List<Person> _people;
  //...
  void MakeFriends() {
    var peter = FindAnOtherPerson(); //from _people 
    var rel = new Relationship(this, peter); //build a relationship
    //how to pass params? something like Resolve<IRelationship>(this, peter)?
  }
  //...
}

Q2:

interface IParent { }
interface IChild { }
class Parent : IParent {
  private IChild _child;
  public Parent() {
    _child = new Child(this); //parent knows child    
    //With DI, how do I resolve child and pass 'this' to child?
  }
}
class Child : IChild {
  private IParent _parent;
  public Child(IParent p) { //child knows parent
    _parent = p; 
  }
}

I thought about this for awhile but not enough brain juice to work it out. Please help thanks :)

Tom
  • 15,781
  • 14
  • 69
  • 111

1 Answers1

1

It seems to me that you are trying to use dependency injection on entities. This is not the most usual thing to do, since you will probably have many persons in the system and they are short lived, compared to long-lived services that they might use. Those services (such as IFriendFinder and IFriendMaker) would be resolved using a container.

More information here: Why not use an IoC container to resolve dependencies for entities/business objects?

Community
  • 1
  • 1
Steven
  • 166,672
  • 24
  • 332
  • 435
  • Oh, I almost forgot about typed factory. Could that be my answer? but I still fail to understand why di on entities is bad idea? – Tom Nov 28 '12 at 13:02
  • @Tom: It has to do with the ambiguity of entities and the role they play. You can't ask the container "give me IPerson", since there are probably thousands of persons in the system. The container manages services and person is not a service; it's an entity. Instead you can ask a `IUnitOfWork` "give me person 34". An `IUnitOfWork` is a service and this unit of work manages the lifetime of persons. – Steven Nov 28 '12 at 13:11
  • 1
    I am trying to using my way to understand this. It seems like any instance that can be a singleton or 1 to 1 relationship is suitable for DI. If there are multiple instances of a class, then it is not good for DI. – Tom Dec 01 '12 at 00:08