如何在模块中使用container.Resolve?

时间:2013-07-14 00:42:13

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

我是Autofac的初学者。 有谁知道如何在Module中使用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);
        ...
    }
}

如何在模块中获取容器?

2 个答案:

答案 0 :(得分: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);
            ...
        };
    }
}

答案 1 :(得分:0)

您可以使用IActivatingEventArgs Context属性:

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