简体   繁体   English

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

[英]Is it possible to get container type in AutoFac

For example, I have registered class C1 with one parameter in constructor of type System.Type . 例如,我在System.Type类型的构造函数中使用一个参数注册了类C1。 I have another class (C2) with injected parameter of type C1. 我有另一个类(C2),注入参数类型为C1。 And I want receive typeof(C2) automatically in C1 constructor. 我想在C1构造函数中自动接收typeof(C2) Is it possible in some way? 有可能吗?

Example code: 示例代码:

public class C1
{
  public C1(Type type) {}

  // ...
}

public class C2
{
  public C2(C1 c1) {}

  // ...
}

// Registration
containerBuilder.Register(???);
containerBuilder.Register<C2>();

This should do it: 这应该这样做:

builder.RegisterType<C1>();
builder.RegisterType<C2>();
builder.RegisterModule(new ExposeRequestorTypeModule());

Where: 哪里:

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);
        };
    }
}

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. 任何采用System.Type参数的组件都将获取传递给它的请求者的类型(如果有的话)。可能的改进可能是使用NamedParameter而不是TypedParameter来限制将仅与具有a匹配的Type参数匹配某个名字。

Please let me know if this works, others have asked about the same general task and this would be good to share with them. 如果这有效,请告诉我,其他人已经询问了相同的一般任务,这将很好地与他们分享。

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

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