繁体   English   中英

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

[英]Is it possible to get container type in 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>();

这应该这样做:

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来限制将仅与具有a匹配的Type参数匹配某个名字。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM