是否可以在AutoFac中获取容器类型 [英] Is it possible to get container type in AutoFac

查看:49
本文介绍了是否可以在AutoFac中获取容器类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我在类型System.Type的构造函数中用一个参数注册了类C1.我有另一个具有C1类型注入参数的类(C2).我想在C1构造函数中自动接收typeof(C2).有可能吗?

For example, I have registered class C1 with one parameter in constructor of type System.Type. I have another class (C2) with injected parameter of type C1. And I want receive typeof(C2) automatically in C1 constructor. Is it possible in some way?

示例代码:

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来限制Type参数只会与具有特定名称的人匹配.

Any component that takes a System.Type parameter will get the type of the requestor passed to it (if any.) A possible improvement might be to use a NamedParameter rather than TypedParameter to restrict the Type parameters that will be matched to only those with a certain name.

请让我知道是否可行,其他人也问过相同的一般任务,可以与他们分享.

Please let me know if this works, others have asked about the same general task and this would be good to share with them.

这篇关于是否可以在AutoFac中获取容器类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆