Search code examples
c#resourcesuwpdynamic-library

UWP - How to use Resources.resw in class library


in library

        public string GetName()
    {
        ResourceLoader rl = ResourceLoader.GetForCurrentView("ClassLibrary1/Resources");

        return rl.GetString("Name");
    }

at "ResourceLoader rl = ResourceLoader.GetForCurrentView("ClassLibrary1/Resources");"

An exception of type 'System.Runtime.InteropServices.COMException' occurred in ClassLibrary1.dll but was not handled in user code

WinRT information: 未找到 ResourceMap。

Additional information: 未找到 ResourceMap。

未找到 ResourceMap。

If there is a handler for this exception, the program may be safely continued.

if i add reference this library , it is working well. but i Dynamic reference this library ,it is failure.

        Assembly assembly = Assembly.Load(new AssemblyName("ClassLibrary1"));
        if (assembly == null)
        {
            return;
        }
        Type type = assembly.GetType("ClassLibrary1.Class1");
        ICore core = Activator.CreateInstance(type) as ICore;
        textBlock1.Text = core.GetName();

        //ClassLibrary1.Class1 c1 = new ClassLibrary1.Class1();
        //textBlock1.Text = c1.GetName(); //it is working well

how to use resources for Dynamic reference in the library?


Solution

  • if i add reference this library , it is working well. but i Dynamic reference this library ,it is failure.

    Most of your code is right, you didn't mention what exactly the exception is. Here is my demo:

    Portable class library, class1:

    public class Class1
    {
        public Class1()
        {
            Debug.WriteLine("ClassLib Loaded!");
        }
    
        public void Output()
        {
            Debug.WriteLine("ClassLib method!");
        }
    }
    

    In UWP app:

    Assembly assembly = Assembly.Load(new AssemblyName("ClassLibrary1"));
    if (assembly == null)
    {
        return;
    }
    Type type = assembly.GetType("ClassLibrary1.Class1");
    object obj = Activator.CreateInstance(type);
    var method = type.GetMethod("Output");
    method.Invoke(obj, null);
    

    The output in the immediate window is like this:

    enter image description here

    To do this, you will need to:

    1. build your class library.

    2. right click your class lib, choose "Open folder in File Explorer", in the folder find the "bin" folder => "Debug", copy the ClassLibrary1.dll into your UWP project like this:

    enter image description here

    Although doing this can solve the problem, but in my personal opinion, it seems not easier than directly adding reference of this library.