views:

43

answers:

1

I'm using a 3rd party library which requires a static method to be invoked before it is used - it sets the serial key to validate the license for the software. I'm needing to use this library in multiple projects and I want to shield those projects from needing to worry about this license. Ideally, I'd like to create a shared assembly which will handle the licensing and reference it by the projects which use the library - and isolate those projects from even knowing that any licensing is taking place.

One way to start thinking about accomplishing this is to perhaps use an assembly attribute. So, I make one which has a contructor to set the license:

[AttributeUsage(AttributeTargets.Assembly)]
public class LibraryLicenseAttribute : Attribute
{
  public LibraryLicenseAttribute()
  {
    Lib.SetLicense("valid key");
  }
}

and place it in a wrapper project:

LibraryWrapperProject
  Properties
    AssemblyInfo.cs
  References
    Lib.dll
  LibraryLicenseAttribute.cs

And have it invoked by including it in AssemblyInfo.cs:

[LibraryLicense]

Now, I can reference this project in another project which uses the library:

LibraryUserProject
  References
    LibraryWrapperProject
  LibraryUser.cs

... but when I go to use the library ...

class LibraryUser
{
  public LibraryUser()
  {
    Lib.Use();
  }
}

It reports that the license hasn't been set. I've found that I can include the attribute in the calling project's AssemblyInfo.cs and the attribute will get invoked. This is better than redistributing the licensing to all the downstream projects, but they still need that extra cruft to make it work.

Furthermore - some of the projects are dynamically loaded elseware. For instance:

Assembly.Load("LibraryUserProject.dll");

How can I invoke the licensing assembly attribute when dynamically loading the assembly it is contained in? Is there another .NET framework feature that might make this easier?

A: 

Without much analysing your solution to the problem, i suggest you to check out the AppDomain.CurrentDomain.AssemblyLoad and AppDomain.AssemblyResolve events for running your code when the assembly resolved or loadded.

Another and more elegant solution may be using a static type initializers (static constructor) or Module Initializers. Static type intitializers are called the first time the type is referenced and easy to implement. However, Module Initializers in C# is not a trivial task but you can achive your goal by implementing.

orka
What I was looking for is the Module Initializer, but the non-trivial implementation is a bit of a bummer.
James Kolpack