是否可以在AutoFac中获取容器类型

时间:2011-01-23 14:23:28

标签: c# dependency-injection 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<C2>();

1 个答案:

答案 0 :(得分:7)

这应该这样做:

builder.RegisterType<C1>();
builder.RegisterType<C2>();
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来限制仅与具有特定名称的那些匹配的Type参数。

如果有效,请告诉我,其他人已经询问了相同的一般性任务,与他们分享会很好。