How to register All types of an interface and get instance of them in unity?

匆匆过客 提交于 2019-11-27 18:14:37

问题


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

回答1:


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();


来源:https://stackoverflow.com/questions/23325902/how-to-register-all-types-of-an-interface-and-get-instance-of-them-in-unity

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