我可以使用构造函数参数注册一个类型,并在解析它时传递一个参数吗?基本上结合参数?
builder.RegisterType<Foo>()
.WithParameter((p, c) => p.Name == "session"
, (p, c) => {
return FindTheSession();
}
);
//somewhere else in the code
((AutofacDependencyResolver)DependencyResolver.Current).RequestLifetimeScope.Resolve(typeof(Foo), new NamedParameter("instance", this));
public class Foo
{
public Foo(object session, object instance) {}
}
答案 0 :(得分:2)
我会做这样的注册:
builder
.Register((c, p) => new Foo(
c.ResolveKeyed<object>("session"),
p.Named<object>("instance")));
builder
.Register(c => FindTheSession())
.Keyed<object>("session");
当然,如果session
是唯一类型而不仅仅是object
,那么您只需注册并将其解析为类型,而不必使用Keyed
语法。< / p>