0

For example I have dependency:

public interface IMyDependency
{
}

public class MyDependency : IMyDependency
{
}

That injects in MyClass object:

public interface IMyInterface
{
}

public class MyClass : IMyInterface
{
    [Dependency]
    public IMyDependency MyDependency { get; set; }
}

Also I have a Factory, that creates MyClass instance:

public interface IFactory
{
    IMyInterface CreateMyObject();
}


public class Factory : IFactory
{
    public IMyInterface CreateMyObject()
    {
       // some checks before creation
       // for. ex check if this type of object supported by OS and thow    exception if not

         return new MyClass();
    }
}

...
container.RegisterType<IFactory, Factory>();

If I create MyClass instance with "new" keyword my dependencies will not be resolve. Or I should escape from Factory and move logic into constructor of MyClass? And after register it in container like container.RegisterType()?

Hopeless
  • 579
  • 1
  • 8
  • 25

1 Answers1

0

For dependencies that are independent of the instance you're creating, inject them into the factory and store them until needed.

For dependencies that are independent of the context of creation but need to be recreated for each created instance, inject factories into the factory and store them.

For dependencies that are dependent on the context of creation, pass them into the Create method of the factory.

Haukinger
  • 10,420
  • 2
  • 15
  • 28