【问题标题】:Is it possible to get container type in AutoFac是否可以在 AutoFac 中获取容器类型
【发布时间】:2011-09-29 21:06:00
【问题描述】:

例如,我在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>();

【问题讨论】:

    标签: c# dependency-injection autofac


    【解决方案1】:

    应该这样做:

    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 参数只会与具有特定名称的人匹配。

    如果这可行,请告诉我,其他人问过同样的一般任务,这将是很好的与他们分享。

    【讨论】:

    • 不,很遗憾,它不起作用。 LimitType 是组件本身的类型(在本例中为 C1)
    • 啊 - 啊! - 感谢那。如果我发现任何替代方案,我会考虑并在此处发布。
    • 主要问题在 AutowiringParameter。它总是为没有参数的子项调用解析(可枚举为空)。我创建了类似的参数并将其注册在registration.ActivatorData.ConfiguredParameters(其中ActivatorData是ReflectionActivatorData)中,其值为:registration.ActivatorData.ImplementationType。但它仅适用于显式 c.Resolve (并且通过注入 C1 本身,我得到了 C1 的 'Non of constructors found...')..
    • 嗨-我已经更新了答案,希望能解决这个问题。让我知道你是否可以试一试。
    • 是的,它有效(我刚刚将 pi.DeclaringType 更改为 pi.Member.DeclaringType)。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    相关资源
    最近更新 更多