了解AutoFac Captive-dependencies

时间:2016-12-13 12:33:49

标签: c# autofac

请原谅我,我只是AutoFac的新手,我才开始学习它是如何运作的。当我在官方网站上阅读Captive-Dependencies时,我有一些问题要理解Captive-dependencies和sope Lifetime

让我困惑的是帖子中提到的例子。请仔细阅读以下评论。感谢。

原来的解释看起来很自然。我刚刚在这里引用它。

public class RuleManager
{
  public RuleManager(IEnumerable<IRule> rules)
  {
      this.Rules = rules;
  }

  public IEnumerable<IRule> Rules { get; private set; }
}

public interface IRule { }

public class SingletonRule : IRule { }

public class InstancePerDependencyRule : IRule { }


[Fact]
public void CaptiveDependency()
{
    var builder = new ContainerBuilder();

    // The rule manager is a single-instance component. It
    // will only ever be instantiated one time and the cached
    // instance will be used thereafter. It will be always be resolved
    // from the root lifetime scope (the container) because
    // it needs to be shared.
    builder.RegisterType<RuleManager>()
           .SingleInstance();

    // This rule is registered instance-per-dependency. A new
    // instance will be created every time it's requested.
    builder.RegisterType<InstancePerDependencyRule>()
           .As<IRule>();

    // This rule is registered as a singleton. Like the rule manager
    // it will only ever be resolved one time and will be resolved
    // from the root lifetime scope.
    builder.RegisterType<SingletonRule>()
           .As<IRule>()
           .SingleInstance();

    using (var container = builder.Build())
    using (var scope = container.BeginLifetimeScope("request"))
    {
      // The manager will be a singleton. It will contain
      // a reference to the singleton SingletonRule, which is
      // fine. However, it will also hold onto an InstancePerDependencyRule
      // which may not be OK. The InstancePerDependencyRule that it
      // holds will live for the lifetime of the container inside the
      // RuleManager and will last until the container is disposed.
      var manager = scope.Resolve<RuleManager>();
    }
}

阅读之后,我有一些问题和理解,如下所示。请帮忙查看一下。

  1. using语句完成时,范围的生​​命周期(container.BeginLifetimeScope(“request”))结束时,组件的哪个实例将是一次性的? InstancePerDependencyRuleRuleManager
  2. 我的回答是InstancePerDependencyRule将是一次性的。这样对吗?原因显示在2。

    1. 为什么InstancePerDependencyRule生命周期长于Rulemanger?而这个例子说它反对Captive-dependencies规则。请更准确地解释一下。根据我的理解,它默认注册为Instance-per-dependency。在scope(container.BeginLifetimeScope(“request”))结束后,它将是一次性的。 (因为它由using语句包装)。我认为InstancePerDependencyRule生命周期应该短于RuleManger Singleton
    2. 如果我的理解有任何问题,请帮助纠正我。感谢。

0 个答案:

没有答案