开发者

How do I register types in assemblies that haven't been loaded with Unity?

开发者 https://www.devze.com 2023-04-13 01:27 出处:网络
I want to load all the types of an Interface so I can call a method on it. However, the assemblies are not referenced a compile time. They will be in the bin folder.

I want to load all the types of an Interface so I can call a method on it. However, the assemblies are not referenced a compile time. They will be in the bin folder.

Is this something I can do easily with Unity?

So for example I have code sort of like:

using (var container = new UnityContainer())
        {
            container.RegisterType<IModule>();

            var modules = container.ResolveAll(typeof(IModule));

            foreach (IModule module in modules) { module.Logon(); }

            Console.WriteLine("Done...");
            Console.ReadLine();
        }

Of course, modules resolves to nothing because the assemblies have been just dropped into the bin fol开发者_StackOverflowder. They are not statically referenced in my current assembly.

Or, do I have to do some type of Assemblies.LoadAssembly(). I'd like this to be as dynamic as possible. I don't have to have to specify assembly names in a config file or code if possible.

Thanks in advance.


Unity does not, by itself, load any assemblies. It works off Type objects and lets the CLR load those types however it wants to.

To do dynamic discovery like you want, you'll need to write a little code to spin through the assemblies in the bin directory, load them into memory, and then spin through them looking for the types you're interested in. It's pretty trivial if you're familiar with the reflection APIs.

Here's some code you can use to loop through the bin directory and make sure every assembly there is loaded:

    private static bool ForceLoadAssemblies()
    {
        foreach (var fileName in Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath, "*.dll"))
        {
            string assemblyName = Path.GetFileNameWithoutExtension(fileName);
            if (assemblyName != null)
            {
                Assembly.Load(assemblyName);
            }
        }
        return true;
    }

Another option would be to look at MEF instead. MEF was explicitly designed for the dynamic discovery case, while Unity is more built around internal dependency management.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号