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();
}
}
Unity 3 added registration by convention to do the mass registration.
Also, Unity has the concept of registering an unnamed mapping and many named mappings. The unnamed mapping will be resolved when calling Resolve() or one of its overloads. All of the named mappings (and not the unnamed mapping) will be resolved when calling ResolveAll() or one of its overloads.
// There's other options for each parameter to RegisterTypes()
// (and you can supply your own custom options)
container.RegisterTypes(
AllClasses.FromLoadedAssemblies().
Where(type => typeof(IRunOnEachRequest).IsAssignableFrom(type)),
WithMappings.FromAllInterfaces,
WithName.TypeName,
WithLifetime.Transient);
foreach (var task in container.ResolveAll<IRunOnEachRequest>())
task.Execute();