Autofac装饰器+代表工厂 [英] Autofac decorator + delegate factory
问题描述
我试图在Autofac中使用带有委托工厂的装饰器,但是我似乎无法通过它来解析参数.
I am trying to use a decorator in Autofac with a delegate factory but I can't seem to get it to resolve the parameters.
public interface IFoo
{ }
public class Foo : IFoo
{
public Foo(string bar)
{ ... }
}
public class DecoratedFoo : IFoo
{
public DecoratedFoo(IFoo decorated)
{ ... }
}
我想注入这样的服务:
public SomeService(Func<string, IFoo> factory)
{
// I would expect IFoo to be a DecoratedFoo here
IFoo foo = factory("hello");
}
我已经注册了以下组件:
I have registered components like so:
builder.RegisterType<Foo>()
.Named<IFoo>("foo")
.UsingConstructor(typeof(string));
builder.RegisterDecorator<IFoo>(
(ctx, inner) => new DecoratedFoo(inner),
fromKey: "foo");
我收到一条错误消息,提示它无法解析我的参数栏.这是一个简化的示例,但我不知道bar的值是什么(因此使用工厂).
I get an error saying it cannot resolve my parameter bar. This is a simplified example but I won't know what the value of bar is (hence using the factory).
有什么方法可以完成我的工作吗?
Is there any way to accomplish what I'm doing?
推荐答案
使用RegisterDecorator
时-它不会传播字符串参数,您将传递给工厂的更深的Foo
构造函数.这是有关此问题的公开问题.所以在这行上
When you use RegisterDecorator
- it will not propagate string parameter you pass to your factory deeper to your Foo
constructor. Here is an open issue about that. So on this line
IFoo foo = factory("hello");
它将抛出异常(如您所观察到的),因为它将尝试查找Foo
的无参数构造函数,并且没有.
It will throw exception (as you observe) because it will try to find parameterless constructor of Foo
and there is none.
要解决此问题,您可以删除您的RegisterDecorator
,而改为手动进行:
To fix, you can remove your RegisterDecorator
and instead do that manually:
builder.RegisterType<Foo>()
.Named<IFoo>("foo");
builder.Register((cnt, parameters) =>
new DecoratedFoo(cnt.ResolveNamed<IFoo>("foo", parameters))).As<IFoo>();
几乎相同数量的代码,但是可以正常工作,因为您可以手动传播参数.
Almost the same amount of code, but works as expected, because you manually propagate parameters.
这篇关于Autofac装饰器+代表工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!