How better to resolve dependencies in object created by factory?

不打扰是莪最后的温柔 提交于 2019-11-26 14:58:49

问题


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()?


回答1:


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.



来源:https://stackoverflow.com/questions/39768318/how-better-to-resolve-dependencies-in-object-created-by-factory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!