February 6, 2017

Loading Dll from Embedded Resource to SSIS Script Component

1) Add dll file as a reference.
2) Added dll must be saved in the project as a Embedded Resource.
        a) Right click on the added dll file
        b) Build Action -> Embedded Resource
        c) Copy to Output Directory -> Do not Copy


Use the script below:

 static ScriptMain()
    {
        AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
    }
    static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
    {
        Assembly executingAssembly = Assembly.GetExecutingAssembly();

        if (args.Name.Contains("AddedFile1"))
        {
            if (AddedFile1 == null)
            {
                using (Stream stream = executingAssembly.GetManifestResourceStream("AssemblyName.AddedFile1.dll"))
                {
                    byte[] assemblyRawBytes = new byte[stream.Length];
                    stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length);
                    IdentityModel = Assembly.Load(assemblyRawBytes);
                }
            }
            return AddedFile1;
        }
        else if (args.Name.Contains("AddedFile2"))
        {
            if (Newtonsoft == null)
            {
                using (Stream stream = executingAssembly.GetManifestResourceStream("AssemblyName.AddedFile2.dll"))
                {
                    byte[] assemblyRawBytes = new byte[stream.Length];
                    stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length);
                    Newtonsoft = Assembly.Load(assemblyRawBytes);
                }
            }
            return AddedFile2;
        }
        return null;
    }

We can get AssemblyName from the properties of the script component project.

No comments: