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

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

问题描述

我有一些code,它看起来是这样的:

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

那么,什么是做到这一点的最好办法,仍然没有一个具体的实例newed了?

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?

推荐答案

大部分的答案这里为止建议您更改注入的依赖关系类型某种的抽象工厂(A Func键< T> 也是一个抽象工厂)来解决这个问题。但是,如果你这样做,这将是一个漏水的抽象因为你让一个特定的实施知识决定了消费者的设计。这违反了里氏替换原则

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