c# – 每个匹配生命周期范围的实例,默认情况下?

前端之家收集整理的这篇文章主要介绍了c# – 每个匹配生命周期范围的实例,默认情况下?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在Autofac中为每个匹配的生命周期范围注册创建一个实例,但偶尔需要从全局容器(没有匹配的生命周期范围)请求实例.在没有匹配的生命周期范围的情况下,我想提供一个顶级实例而不是抛出异常.

这可能吗?

@H_502_4@

解决方法

我认为你最好通过引入新的生命周期选项来扩展Autofac.我使用了Autofac源并对其进行了一些修改
  1. public static class RegistrationBuilderExtensions
  2. {
  3. public static IRegistrationBuilder<TLimit,TActivatorData,TRegistrationStyle> InstancePerMatchingOrRootLifetimeScope<TLimit,TRegistrationStyle>(this IRegistrationBuilder<TLimit,TRegistrationStyle> builder,params object[] lifetimeScopeTag)
  4. {
  5. if (lifetimeScopeTag == null) throw new ArgumentNullException("lifetimeScopeTag");
  6. builder.RegistrationData.Sharing = InstanceSharing.Shared;
  7. builder.RegistrationData.Lifetime = new MatchingScopeOrRootLifetime(lifetimeScopeTag);
  8. return builder;
  9. }
  10. }
  11.  
  12. public class MatchingScopeOrRootLifetime: IComponentLifetime
  13. {
  14. readonly object[] _tagsToMatch;
  15.  
  16. public MatchingScopeOrRootLifetime(params object[] lifetimeScopeTagsToMatch)
  17. {
  18. if (lifetimeScopeTagsToMatch == null) throw new ArgumentNullException("lifetimeScopeTagsToMatch");
  19.  
  20. _tagsToMatch = lifetimeScopeTagsToMatch;
  21. }
  22.  
  23. public ISharingLifetimeScope FindScope(ISharingLifetimeScope mostNestedVisibleScope)
  24. {
  25. if (mostNestedVisibleScope == null) throw new ArgumentNullException("mostNestedVisibleScope");
  26.  
  27. var next = mostNestedVisibleScope;
  28. while (next != null)
  29. {
  30. if (_tagsToMatch.Contains(next.Tag))
  31. return next;
  32.  
  33. next = next.ParentLifetimeScope;
  34. }
  35.  
  36. return mostNestedVisibleScope.RootLifetimeScope;
  37. }
  38. }

只需将这些类添加到项目中,并将组件注册为:

  1. builder.RegisterType<A>.InstancePerMatchingOrRootLifetimeScope("TAG");

我自己没试过,但它应该有用.

@H_502_4@ @H_502_4@

猜你在找的C#相关文章