2013-07-14 99 views
2

我是Autofac的初學者。 有誰知道如何在模塊中使用container.Resolve?如何在模塊中使用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); 
     ... 
    } 
} 

如何獲取模塊中的容器?

+0

你想達到什麼目的?爲什麼在'AttachToComponentRegistration'中需要這個?因爲當調用'AttachToComponentRegistration'時,Autofac仍處於容器構建階段,所以你不能使用同一個容器來解析它的類型... – nemesv

+0

我同意@nemesv。如果你想在建造階段解決某些問題,那麼你做錯了什麼。請允許我們通過解釋您要實現的目標以及爲什麼向您提供反饋意見。 – Steven

+0

Autofac的目的是提供動態代理。 我想在構建階段解決一些問題,因爲我希望構建階段的每個代碼都可以動態調用某個類並使用解析方法。 (越來越動態) 我的想法是錯誤的? Ioc本身不能動態? – Flash

回答

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