实例?我想在Autofac中为每个匹配的生命周期范围注册一个实例,但偶尔需要从全局容器中请求一个实例(没有匹配的生命周期范围)。在没有匹配的生命周期范围的情况下,我想提供一个顶级实例而不是抛出异常。是否可以?我认为您最好通过引入新的生命周期选项来扩展Autofac。我使用了Autofac源及其进行了一些修改:builder.RegistrationData.Sharing=InstanceSharing.Shared;builder.RegistrationData.Lifetime=newMatchingScopeOrRootLifetime(lifetimeScopeTag);返回生成器;}}publicclassMatchingScopeOrRootLifetime:IComponentLifetime{readonlyobject[]_tagsToMatch;publicMatchingScopeOrRootLifetime(paramsobject[]lifetimeScopeTagsToMatch){如果(lifetimeScopeTagsToMatch==null)thrownewArgumentNullException("lifetimeScopeTagsToMatch");_tagsToMatch=lifetimeScopeTagsToMatch;}publicISharingLifetimeScopeFindScope(ISharingLifetimeScopemostNestedVisibleScope){如果(mostNestedVisibleScope==null)thrownewArgumentNullException("mostNestedVisibleScope");varnext=mostNestedVisibleScope;while(next!=null){if(_tagsToMatch.Contains(next.Tag))returnnext;next=next.ParentLifetimeScope;}returnmostNestedVisibleScope.RootLifetimeScope;添加到项目中,并注册组件为:builder.RegisterType.InstancePerMatchingOrRootLifetimeScope("TAG");我自己没有尝试过,但它应该可以工作。一个可能的解决方案是覆盖子生命周期范围内的注册。范例:以上是C#学习教程:匹配生命周期范围的每个实例,默认情况下?如果分享的内容对你有用,需要了解更多C#学习教程,希望你多多关注——publicenumScopes{TestScope}publicclassTest{publicstringDescription{get;放;}}publicclassTester{publicvoidDoTest(){ContainerBuilderbuilder=newContainerBuilder();builder.RegisterType().OnActivating(args=>args.Instance.Description="FromRoot").SingleInstance();varcontainer=builder.Build();varscope=container.BeginLifetimeScope(Scopes.TestScope,b=>b.RegisterType().InstancePerMatchingLifetimeScope(Scopes.TestScope).OnActivating(args=>args.Instance.Description="FromScope"));vartest1=container.Resolve();Console.WriteLine(test1.Description);//写入FromRootvartest2=scope.Resolve();Console.WriteLine(test2.Description);//写入FromScopeConsole.ReadLine();}}本文来自网络收藏,不代表立场,如涉及侵权,请点击右边联系管理员删除。如需转载请注明出处:
