依赖注入 - 几种类方法中需要的新实例 [英] Dependency Injection - new instance required in several of a classes methods

查看:117
本文介绍了依赖注入 - 几种类方法中需要的新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码看起来像这样:

  public MyService(IDependency dependency)
{
_dependency =依赖;
}

public Message Method1()
{
_dependency.DoSomething();

}

public Message Method2()
{
_dependency.DoSomething();
}

public Message Method2()
{
_dependency.DoSomething();
}

现在我刚刚意识到,因为依赖对象包含内部状态信息。我需要在每个方法调用中新建一个新的实例。



那么最好的方法是什么,还没有一个具体的实例被新增? p>

您将使用IoC容器,并在每个方法中调用容器?还是有一个狭窄的方式,你只能打一个电话到集装箱?



如果我没有使用IoC容器 - 会有办法不在每种方法中新建一个具体实例?

解决方案

到目前为止,这里的大多数答案建议您将注入的依赖关系类型更改为某种抽象工厂(一个 Func< T> 也是一个抽象工厂)来解决这个问题。但是,如果这样做,那么这将是一个泄漏抽象,因为您可以让具体实现的知识确定消费者的设计。这违反了 Liskov替代原则



更好的选择是让保持MyService ,然后为IDependency创建一个解决特定生命周期问题的包装器:

  public class TransientDependencyWrapper:IDependency 
{
public void DoSomething()
{
new MyStatefulDependency()DoSomething();
}
}

将其注入MyService,而不是直接注入原始实现(MyStatefulDependency)。



如果要抽象出依赖关系的创建,您可以随时在此级别注入抽象工厂。


I have some code that looks something like this:

public MyService(IDependency dependency)
{
    _dependency = dependency;
}

public Message Method1()
{
    _dependency.DoSomething();

}

public Message Method2()
{
    _dependency.DoSomething();  
}

public Message Method2()
{
    _dependency.DoSomething();  
}

Now I have just realised that because the dependency object contains internal state information. I need to new up a new instance of it in each method call

So what is the best way to do this and still not have a concrete instance newed up ?

Would you use an IoC container and make a call to to the container in each and every one of the methods? Or is there a slicker way where you can only make one call to the container?

What if I wasn't using an IoC container - would there be a way to not new up a concrete instance in each method?

解决方案

Most of the answers here so far suggest that you change the injected dependency type to some sort of Abstract Factory (a Func<T> is also an Abstract Factory) to address the issue. However, if you do that it would be a leaky abstraction because you would let the knowledge of a particular implementation determine the design of the consumer. This violates the Liskov Substitution Principle.

A better option is to keep MyService as it is, and then create a wrapper for IDependency that addresses the particular lifetime issue:

public class TransientDependencyWrapper : IDependency
{
    public void DoSomething()
    {
        new MyStatefulDependency().DoSomething();
    }
}

Inject that into MyService instead of directly injecting the original implementation (MyStatefulDependency).

If you want to abstract away the creation of the dependency, you can always inject an Abstract Factory at this level.

这篇关于依赖注入 - 几种类方法中需要的新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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