2

I am beginner with Autofac. Does anyone know How to using container.Resolve in Module?

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

How does I get container in module?

Flash
  • 1,615
  • 4
  • 17
  • 23
  • What are you trying to achieve? Why you need this in the `AttachToComponentRegistration`? Because when the `AttachToComponentRegistration` gets invoked Autofac is still in the container building "phase" so you cannot use the same container to resolve types from it... – nemesv Jul 14 '13 at 06:16
  • I agree with @nemesv. If you want to resolve something during the building phase, you are doing something wrong. Please allow us to give you feedback on this by explaining what you're trying to achieve and why. – Steven Jul 14 '13 at 13:50
  • Autofac purpose is provide dynamic proxies. I want to resolve something during the building phase, beacuse I hope every code in building phase also dynamic call some class with resolve method. (more and more dynamic) My idea is wrong? Ioc itself can not be dynamically ? – Flash Jul 17 '13 at 12:37

2 Answers2

0

You cannot resolve component from container in the module. But you can attach to each component resolution events individually. So when you meet interesting component you can do anything with it. It can be said that conceptually you resolving component.

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);
            ...
        };
    }
}
Eugene
  • 389
  • 1
  • 7
  • 18
0

You can use IActivatingEventArgs Context property:

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