c# - 典型的 IoC 容器用法——向下传递数据

标签 c# .net unity-container ioc-container

我最近开始使用 IoC容器,但我没有接受过使用它的最佳实践方面的教育。更具体地说,我正在使用 Unity在 C# .NET 项目中,我开始使用它,因为它带有 Prism .

我使用容器来解析“顶级”对象,它们根据容器获得正确的注入(inject)对象。但是,当我有一个带有 child 和 child 的 child 的对象时,我无法清楚地看到最佳实践,并且我需要 IoC 容器中的一些数据一直向下,而不是介于两者之间。您通常如何组织 IoC 容器的使用?

最初我认为您会在需要的地方传递容器,而不是从顶层的容器中提取所需的数据并继续传递这些数据。但话又说回来,当我到达除了注入(inject)接口(interface)之外还采用其他特定数据的对象时,我又遇到了问题,我不希望在解析对象后通过属性或初始化方法注入(inject)这些数据。

我希望这已经足够清楚了,但让我们看一个虚构的(有点愚蠢..)的例子。

class Employee
{
    private ICommands _commands; 
    priate List<Customer> _customers = new List<Customer>(); 
    public Employee(ICommands commands)
    {
        _commands = commands; 
    }
    public void AddCustomer(string customerName)
    {
        var customer = new Customer(customerName, _commands); 
        _customers.Add(customer); 
    }
}

class Customer 
{
    private string _name; 
    private ICommands _commands; 
    priate List<Case> _cases = new List<Case>(); 
    public Customer(string, name, ICommands commands)
    {
        _name = name; 
        _commands = commands; 
    }
    public void AddCase()
    {
        var case = new Case(_commands); 
        _cases.Add(case); 
    }
}

class Case    {
    private ICommands _commands; 
    public Customer(ICommands commands)
    {
        _commands = commands; 
    }
    public void TriggerCommands()
    {
        _command.TriggerSomething(); 
    }
}

所以,这个例子其实没什么意义,但本质和我要做的是一样的。我有一些应用程序命令通过我的 ViewModel 类向下传递,因为其中一些需要能够触发命令来显示某些内容。我还有公共(public)存储等,有些类可能需要这些,但目前是通过并存储在中间类中的。只有命令,如果你存储命令或容器,这没什么大不了的,但是在典型的 IoC 用法中,一个人会传递 IoC 容器,并使用它来解析对象吗?客户姓名等特定数据又如何呢?你不能只将它传递给 Resolve(),所以你需要在之后注入(inject)它?

抱歉 - 这是我能做到的最短的。不需要相同长度的答案 ;-) .. 只是;使用 IoC 容器执行此类操作的最佳做​​法是什么?

最佳答案

我不太确定我是否理解您的问题。但我认为你根本不应该传递容器。为容器创建一个包装器类要容易得多。例如:

public class IoCContainer
{
  private static ContainerType = null;

  public static ContainerType Instance 
  {
    get 
    {
      if (_container == null)
      {
        string configFileName = ConfigurationManager.AppSettings[ConfigFileAppSettingName];
        _container = new WindsorContainer(new XmlInterpreter(configFileName));
      }

      return _container;
    }
  }
}

现在您可以在代码中的任何地方调用它。

IoCContainer.Instance.Resolve<IAwesomeService>(); 

这对你有帮助吗?

关于c# - 典型的 IoC 容器用法——向下传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1612682/

相关文章:

c# - 加法后小数点太多

c# - 输入箭头键时如何防止MDI子窗体发生变化?

.net - RDL 2008 架构和 RDL 2010 架构有什么区别?功能明智

c# - 从具有父引用的对象创建嵌套的项目列表

c# - 如何将字符串转换为 BinaryExpression 对象?

c# - 如何在解耦数据层中设置主键

.net - 执行集成测试时如何从 .Net 应用程序中隔离坏的 COM 组件 (HP Quality Center 10.0)

c# - 如何使用 Unity 注入(inject)我的 dbContext

c# - 在 Unity 中解析和注册项目数组

c# - 单元测试 unityContainer.Resolve