问题
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