How unity can get all instances of an interface and then access them?
Code pieces are taken from here : Fail-Tracker
In StrcutureMap its possible to register all types of an interface from an assembly and then access them like following:
public class TaskRegistry : Registry
{
public TaskRegistry()
{
Scan(scan =>
{
scan.AssembliesFromApplicationBaseDirectory(
a => a.FullName.StartsWith("FailTracker"));
scan.AddAllTypesOf<IRunAtInit>();
scan.AddAllTypesOf<IRunAtStartup>();
scan.AddAllTypesOf<IRunOnEachRequest>();
scan.AddAllTypesOf<IRunOnError>();
scan.AddAllTypesOf<IRunAfterEachRequest>();
});
}
}
ObjectFactory.Configure(cfg =>
{
cfg.AddRegistry(new TaskRegistry());
});
and then access all types implementing those interfaces like:
using (var container = ObjectFactory.Container.GetNestedContainer())
{
foreach (var task in container.GetAllInstances<IRunAtInit>())
{
task.Execute();
}
foreach (var task in container.GetAllInstances<IRunAtStartup>())
{
task.Execute();
}
}
What is the equivalent of this code in unity?
How can i get these at Application_BeginRequest like structuremap
public void Application_BeginRequest()
{
Container = ObjectFactory.Container.GetNestedContainer();
foreach (var task in Container.GetAllInstances<IRunOnEachRequest>())
{
task.Execute();
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…