【问题标题】:How to using container.Resolve in Module?如何在模块中使用 container.Resolve?
【发布时间】:2013-07-14 00:42:12
【问题描述】:

我是 Autofac 的初学者。 有谁知道如何在模块中使用 container.Resolve?

public class MyClass
{
  public bool Test(Type type)
    {
       if( type.Name.Begin("My") )  return true;
         return false;
    }
}

public class MyModule1 : Autofac.Module
{
    protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
    {
        var type = registration.Activator.LimitType;
        MyClass my = container.Resolve<MyClass>();  //How to do it in Module? 
        my.Test(type);
        ...
    }
}

如何在模块中获取容器?

【问题讨论】:

  • 你想达到什么目的?为什么在AttachToComponentRegistration 中需要这个?因为当AttachToComponentRegistration 被调用时,Autofac 仍处于容器构建“阶段”,所以你不能使用同一个容器来解析它的类型......
  • 我同意@nemesv。如果您想在构建阶段解决某些问题,那么您做错了什么。请允许我们通过解释您要达到的目标以及原因来向您提供反馈。
  • Autofac 的目的是提供动态代理。我想在构建阶段解决一些问题,因为我希望构建阶段的每个代码也动态调用一些具有解决方法的类。 (越来越有活力)我的想法错了吗? ioc本身不能动态吗?

标签: c# inversion-of-control ioc-container autofac


【解决方案1】:

您无法从模块中的容器解析组件。但是您可以单独附加到每个组件解析事件。所以当你遇到有趣的组件时,你可以用它做任何事情。可以说在概念上你解决了组件。

public class MyModule : Autofac.Module
{
    protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration)
    {
        registration.Activated += (sender, args) =>
        {
            var my = args.Instance as MyClass;
            if (my == null) return;

            var type = args.Component.Activator.LimitType;
            my.Test(type);
            ...
        };
    }
}

【讨论】:

    【解决方案2】:

    您可以使用 IActivatingEventArgs 上下文属性:

    protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration)
        {
            registration.Activated += (sender, args) =>
            {
                args.Context.Resolve<...>();
                ...
            };
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-08
      • 2011-06-07
      • 1970-01-01
      • 1970-01-01
      • 2011-08-04
      • 2016-01-23
      • 2016-05-15
      相关资源
      最近更新 更多