2

我是 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);
        ...
    }
}

如何在模块中获取容器?

4

2 回答 2

0

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

protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration)
    {
        registration.Activated += (sender, args) =>
        {
            args.Context.Resolve<...>();
            ...
        };
    }
于 2019-07-29T16:08:19.537 回答
0

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

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);
            ...
        };
    }
}
于 2017-03-31T11:42:12.293 回答