如何更好地解决工厂创建的对象中的依赖关系? [英] How better to resolve dependencies in object created by factory?

查看:79
本文介绍了如何更好地解决工厂创建的对象中的依赖关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有依赖性:

public interface IMyDependency
{
}

public class MyDependency : IMyDependency
{
}

在MyClass对象中:

That injects in MyClass object:

public interface IMyInterface
{
}

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

我还有一个工厂,可以创建MyClass实例:

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

如果我使用 new关键字创建MyClass实例,我的依赖项将无法解决。还是我应该从Factory逃脱并将逻辑移到MyClass的构造函数中?然后在像container.RegisterType()这样的容器中注册它之后?

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

推荐答案

对于独立于要创建的实例的依赖项,将它们注入工厂并存储直到需要。

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.

对于依赖于创建上下文的依赖项,请将它们传递给 Create 工厂的方法。

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

这篇关于如何更好地解决工厂创建的对象中的依赖关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆