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

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

问题描述

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

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 ?

您是否会使用 IoC 容器并在每个方法中调用该容器?或者有没有一种更巧妙的方法,您只能对容器进行一次调用?

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?

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

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

推荐答案

到目前为止,这里的大多数答案都建议您将注入的依赖类型更改为某种 抽象工厂(Func 也是一个抽象工厂)来解决这个问题.但是,如果您这样做,将成为抽象漏洞,因为您会让特定实现的知识决定消费者的设计.这违反了Liskov 替换原则.

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.

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

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

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

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天全站免登陆