How to using container.Resolve in Module?

和自甴很熟 提交于 2019-12-11 01:19:47

问题


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?


回答1:


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



回答2:


You can use IActivatingEventArgs Context property:

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


来源:https://stackoverflow.com/questions/17635498/how-to-using-container-resolve-in-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!