我将举一个非常简单的例子.
class Implementation: IMyInterface
{
string mArg;
public Implementation(string arg)
{
mArg = arg;
}
public DoStuff(object param)
{
// snip
}
}
class Decorator: IMyInterface
{
IMyInterface mWrapped;
public Decorator(IMyInterface wrapped)
{
mWrapped = wrapped;
}
public DoStuff(object param)
{
var result = mWrapped.DoStuff(param);
// snip
return result;
}
}
现在,我需要实现构造函数的参数,我在运行时从用户那里得到.
IMyInterface GetMyObject()
{
string arg = AskUserForString();
return mContext.Resolve // HOW?
}
那么设置它并解析装饰实例的正确方法是什么?
这个例子很简单.但是想象有更多的层(装饰器/适配器)和最里面的实现需要参数我在运行时获得.
解决方法:
我假设你正在使用autofac,因为它在问题的标签中.
你可以尝试这些方面:
public class ImplementationFactory
{
private readonly IComponentContext container;
public ImplementationFactory(IComponentContext container)
{
this.container = container;
}
public IMyInterface GetImplementation(string arg)
{
return container.Resolve<IMyInterface>(new NamedParameter("arg", arg));
}
}
注册/解决部分:
var builder = new ContainerBuilder();
builder.RegisterType<ImplementationFactory>();
builder.RegisterType<Implementation>().Named<IMyInterface>("implementation");
builder.Register((c, args) => new Decorator(c.ResolveNamed<IMyInterface>("implementation", args.First())))
.As<IMyInterface>();
var container = builder.Build();
var factory = container.Resolve<ImplementationFactory>();
var impl = factory.GetImplementation("abc"); //returns the decorator
如果您有多个装饰器,您可以按照注册中的顺序链接它们:
builder.Register((c, args) => new Decorator(c.ResolveNamed<IMyInterface>("implementation", args.First())));
builder.Register((c, args) => new SecondDecorator(c.Resolve<Decorator>(args.First()))).As<IMyInterface>();
Here is a good article about decorator support in autofac也是.