是否可以在AutoFac中获取容器类型
例如,我在System.Type
类型的构造函数中使用一个参数注册了类C1。 我有另一个类(C2),注入参数类型为C1。 我想在C1构造函数中自动接收typeof(C2)
。 有可能吗?
示例代码:
public class C1 { public C1(Type type) {} // ... } public class C2 { public C2(C1 c1) {} // ... } // Registration containerBuilder.Register(???); containerBuilder.Register();
这应该这样做:
builder.RegisterType(); builder.RegisterType(); builder.RegisterModule(new ExposeRequestorTypeModule());
哪里:
class ExposeRequestorTypeModule : Autofac.Module { Parameter _exposeRequestorTypeParameter = new ResolvedParameter( (pi, c) => c.IsRegistered(pi.ParameterType), (pi, c) => c.Resolve( pi.ParameterType, TypedParameter.From(pi.Member.DeclaringType))); protected override void AttachToComponentRegistration( IComponentRegistry registry, IComponentRegistration registration) { registration.Preparing += (s, e) => { e.Parameters = new[] { _exposeRequestorTypeParameter } .Concat(e.Parameters); }; } }
任何采用System.Type
参数的组件都将获取传递给它的请求者的类型(如果有的话)。可能的改进可能是使用NamedParameter
而不是TypedParameter
来限制将仅与具有a匹配的Type
参数匹配某个名字。
如果有效,请告诉我,其他人已经询问了相同的一般任务,与他们分享会很好。