Is it possible to get container type in AutoFac

前端 未结 1 1999
梦谈多话
梦谈多话 2021-02-09 12:14

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 w

1条回答
  •  孤街浪徒
    2021-02-09 13:03

    This should do it:

    builder.RegisterType();
    builder.RegisterType();
    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.

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

    0 讨论(0)
提交回复
热议问题