如何使用参数在Autofac中注册Type并使用参数解析?

时间:2014-08-12 16:38:01

标签: c# dependency-injection autofac

我可以使用构造函数参数注册一个类型,并在解析它时传递一个参数吗?基本上结合参数?

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) {}
}

1 个答案:

答案 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>