【问题标题】:Autofac, MakeGenericMethod.Invoke not workingAutofac,MakeGenericMethod.Invoke 不起作用
【发布时间】:2016-09-09 07:01:37
【问题描述】:

我尝试使用 Autofac IRegistrationSource 解析其他接口,但它不起作用。下面是我的代码:

public class SettingsSource : IRegistrationSource
{
    static readonly MethodInfo BuildMethod = typeof(SettingsSource).GetMethod(
        "BuildRegistration",
        BindingFlags.Static | BindingFlags.NonPublic);

    public IEnumerable<IComponentRegistration> RegistrationsFor(
            Service service,
            Func<Service, IEnumerable<IComponentRegistration>> registrations)
    {
        var ts = service as TypedService;
        if (ts != null && typeof(ISettings).IsAssignableFrom(ts.ServiceType))
        {
            var buildMethod = BuildMethod.MakeGenericMethod(ts.ServiceType);
            yield return (IComponentRegistration)buildMethod.Invoke(null, null);
        }
    }

    static IComponentRegistration BuildRegistration<TSettings>()
        where TSettings : ISettings, new()
    {
        return RegistrationBuilder
            .ForDelegate((c, p) =>
            {
                return c.Resolve<ISettingService>().LoadSetting<TSettings>();
            })
            .InstancePerLifetimeScope()
            .CreateRegistration();
    }

    public bool IsAdapterForIndividualComponents { get { return false; } }
}

私有方法 c.Resolve().LoadSetting() 不能被触发。

我检查了下面的链接,仍然无法弄清楚原因。 Autofac. How to use custom method(property) to resolve some interface?

http://nblumhardt.com/2010/01/declarative-context-adapters-autofac2/

谁能给个提示?

谢谢

【问题讨论】:

  • 您提供的代码是 nopcommerce 中设置提供商注册的逐字记录副本。因此,您可以确保它按预期工作,否则您将根本没有设置访问权限。你想做什么?
  • 谢谢 Marco,是的,它来自 nopcommerce。我想实现像 nopcommerce 这样的系统设置框架。由 ISettingService 操作并在系统启动时注册的所有设置。但是我发现 fordelegate 中的私有函数没有被触发。
  • 注册源注册了吗?您首先需要调试 RegistrationsFor 方法以确保在解析继承 ISettings 的类时调用并执行 yield return 子句。这里需要设置断点。
  • 是的,可以调用RegistrationsFor,也可以调用BuildRegistration()。但是 LoadSetting() 无法到达。

标签: asp.net .net reflection autofac nopcommerce


【解决方案1】:

nopCommerce 提供的代码完美运行。我自己也用过,效果很好。因此,如果它不起作用,问题将出在您未显示的代码中,但我真诚地怀疑是否存在任何问题,而且很可能它已经在起作用了。

假设达到BuildRegistration 方法,根据您的cmets,它只会返回一个依赖规则,而不是服务实例本身。 c.Resolve&lt;ISettingService&gt;() 调用将稍后在需要时懒惰地执行。您需要在 lambda 中设置断点,才能看到它发生。

请注意,BuildRegistration 只会为每个实现 ISettings 的类调用一次。之后,Autofac 将使用提供的规则。

【讨论】:

  • 你可以在这里查看我之前的回答:stackoverflow.com/questions/32944127/…
  • 谢谢 Marco,正如我提到的 BuildRegistration 可以到达,我已经尝试在 lambda 中设置断点,但是什么也没发生,根本没有触发,这就是我知道 LoadingSetting() 的原因未达到。
  • @LLI,如前所述,您需要提供剩余的代码(autofac注册,设置类和用法),因为您已经提供的代码是正确的。
猜你喜欢
  • 2020-08-23
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 2018-07-20
  • 1970-01-01
  • 1970-01-01
  • 2018-10-24
  • 1970-01-01
相关资源
最近更新 更多