[英]Autofac generic decorator is duplicating components
I have found what I think may be a bug in Autofac, but I wanted to see if anybody had a possible solution or workaround so I can make this work. 我发现我认为可能是Autofac中的一个错误,但我想看看是否有人有可能的解决方案或解决方法,所以我可以做到这一点。
Basically I have set up a generic decorator, which works fine. 基本上我已经设置了一个通用装饰器,它工作正常。 The problem is that as soon as I call BeginLifetimeScope()
with a configuration delegate, it erroneously resolves multiple components of the same type. 问题是,只要我使用配置委托调用BeginLifetimeScope()
,它就会错误地解析同一类型的多个组件。 If I don't use a configuration delegate with BeginLifetimeScope()
, then it works correctly. 如果我没有使用BeginLifetimeScope()
的配置委托,那么它可以正常工作。 Unfortunately, I need to add additional dependencies to my child scope, so not using a configuration delegate is not an option. 不幸的是,我需要在我的子作用域中添加其他依赖项,因此不能使用配置委托。
Here is an example that demostrates the problem: 这是一个解释问题的例子:
var builder = new ContainerBuilder();
builder.RegisterType<Dependency>()
.Named<IDependency<object>>("service");
builder.RegisterGenericDecorator(
typeof(Decorator<>), typeof(IDependency<>), "service", "decorated");
var container = builder.Build();
// Returns 1
var scope1 = container.BeginLifetimeScope();
Console.WriteLine(
scope1.ResolveNamed<IEnumerable<IDependency<object>>>("decorated").Count());
// Returns 2 - notice the configAction doesn't even have to do anything
var scope2 = container.BeginLifetimeScope(r => { });
Console.WriteLine(
scope2.ResolveNamed<IEnumerable<IDependency<object>>>("decorated").Count());
And here are my fake types: 这是我的假类型:
interface IDependency<T> { }
class Dependency : IDependency<object> { }
class Decorator<T> : IDependency<T> {}
Any help would be greatly appreciated! 任何帮助将不胜感激!
It does just seem like a bug. 它看起来像一个bug。 As a workaround, I ended up doing the following: 作为一种解决方法,我最终做了以下事情:
var param = new TypedParameter(typeof(IDecoratorDependency), new DecoratorDependency());
var decorated = scope.ResolveNamed<IEnumerable<IDependency<object>>>("decorated", param);
That was good enough for my use case. 这对我的用例来说已经足够了。 However, this method is inflexible because it only allows me to supply parameters to the root object, in this case Decorator<T>
, but not any of its dependencies. 但是,这种方法不灵活,因为它只允许我向根对象提供参数,在本例中为Decorator<T>
,但不提供任何依赖关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.