Coercing Types and Unloading Assemblies

I was doing a little experimentation recently related to building dynamic assemblies in .NET. One thing I found interesting was that if you create an instance of a dynamic Type then use the “dynamic” keyword to consume it, your dynamic assembly will never be unloaded.

That sort of defeats the purpose if you ask me. I was back to using reflection to call my dynamic objects. Not fun.

So I whipped up a quick dynamic coercion routine. Basically what it does is takes any instance and any interface and builds a wrapper object that implements the interface and calls a matching method on the instance. The instance does not need to implement the interface or even know about it. The coercion method will give the appearance of casting the instance into a interface it doesn’t really implement.

var instance = CreateDynamicAdder();
var adder = instance.Dynamic().Coerce<IAdder>();

Dynamic() is an extension point for type System.Object. Coerce is a extension method:

public static T Coerce<T>(this IDynamicExtensionPoint extensionPoint)
{
    if (!typeof(T).IsInterface)
        throw new ArgumentException("Type T must be an interface.");

    if (extensionPoint == null)
        throw new ArgumentNullException("extensionPoint");

    var assemblyBuilder = Dynamic.CreateDynamicAssembly();
    var wrapperType = BuildWrapperType(
        assemblyBuilder, 
        typeof(T), 
        extensionPoint.Instance.GetType());
    return (T)Activator.CreateInstance(wrapperType, extensionPoint.Instance);
}

So in the first code snippet I get an object that has a method I want to call that I know looks like this:

int Add(int x, int y)

I don’t know the exact Type and I don’t have any interfaces I can cast it into, but I know that this method is there, possibly through documentation, convention or debugging. The Coercion routine will allow me to call dynamic objects with an illusion of strong typing.

So I create an interface that matches the signature I am expecting.

public interface IAdder
{
    int Add(int x, int y);
}

And coerce the instance into this interface. What’s interesting is that when I do it this way, both the dynamic assembly creating the adder as well as the dynamic assembly creating the wrapper are unloaded when I drop references to them.

static void Main(string[] args)
{
    var numberOfAssemblies = AppDomain.CurrentDomain.GetAssemblies().Count();
    Console.WriteLine("Starting assembly count: " + numberOfAssemblies);

    var instance = CreateDynamicAdder();
    var adder = instance.Dynamic().Coerce<IAdder>();
    int z = adder.Add(7, 11);
    Console.WriteLine("Add result: " + z);
    instance = null;
    adder = null;

    numberOfAssemblies = AppDomain.CurrentDomain.GetAssemblies().Count();
    Console.WriteLine("Assembly count before collect: " + numberOfAssemblies);

    GC.Collect();
    GC.WaitForPendingFinalizers();

    numberOfAssemblies = AppDomain.CurrentDomain.GetAssemblies().Count();
    Console.WriteLine("Assembly count after collect: " + numberOfAssemblies);

    Console.ReadKey(true);
}

Here is the resulting screen shot, proving the dynamic assemblies are unloaded.

image

Download the full sample here:

http://cid-dfcd2d88d3fe101c.skydrive.live.com/embedrowdetail.aspx/blog/justnbusiness/DynamicCoerce.zip

Silverlight 4 Runs Natively in .NET

This is a big deal.

I just learned this the other day and found surprisingly little information about it online. It was announced at PDC so it’s not a secret but it seems like a big deal to me. The feature is otherwise known as “assembly portability”.

When doing Silverlight one of the most frustrating things currently is the inability to run unit tests out of browser. This results in a break in continuous integration and a frustrating manual step in your testing process. Well no more!

This is only the beginning of the implications however. If you’re writing any application with a business logical layer, you should probably be writing it in Silverlight exclusively now. No more duplicating projects and creating linked file references. You can literally just create one project, compile it, and run it in both runtimes. Incredible.

Of course there are some limitations. But in this case I almost feel like the limitations are actually benefits. The thing is, you are likely to have features in one environment that are different or inaccessible in another. For example, file system access. In .net if you’re easily accessing the file system, but you might not be able to access it directly in Silverlight in the same way.

Enter System.ComponentModel.Composition. Otherwise known as MEF. By making your application logic composable you can solve all of the problems of framework differences and make your project imminently unit test friendly and better in general (if you buy into the principals of IoC at least).

For example, in Silverlight you cannot get a FileStream directly, you must make a call to OpenFileDialog which will give you the FileStream, if a user allows it. This is all well and good but when running in .net or unit tests you may want to allow it to access the file system directly or give it a mock stream instead. The solution is to make your calls to retrieve streams composable (otherwise known as dependency injection). Create a service interface, and create service instances for different environments.

For example, suppose you have the following (contrived) method in a Silverlight class:

public void DoWork()
{
    var dto = new SimpleDTO { Id = 100, Foo = "Hello World!" };

    Stream stream = Open();
    Save(stream, dto);

    stream = Open();
    dto = Load<SimpleDTO>(stream);

    Console.WriteLine("{0} : {1}", dto.Id, dto.Foo);
}

The process of opening a stream in Silverlight is different from the way it must be done when running in .net. So we make it composable.

public Stream Open()
{
    var stateService = container.GetExport<IStateService>().Value;
    stateService.State.Seek(0, SeekOrigin.Begin);
    return stateService.State;
}

Instead of opening the stream ourselves we import an exported service via MEF, that does know how to do it. To do this we simply need to have access to a container.

private CompositionContainer container;

public ComposableObject(CompositionContainer container)
{
    this.container = container;
}

Our constructor accepts a CompositionContainer as a parameter, which gives us access to all of the composable parts configured for our runtime. Keep in mind this is all Silverlight code at this point. And here is the IStateService.

public interface IStateService : IDisposable
{
    Stream State { get; }
}

The following code snippets are plain-old-dot-net-console-application snippets. First off, here is a snapshot of my solution explorer so you can see how things are structured.

image

You can see that I have created a reference from a Console Application project directly to a Silverlight 4 Class Library project. Visual Studio gives me a yellow banger, presumably because of the framework differences but it builds just fine. My program loads and calls my Silverlight library just this easily:

using SilverlightClassLibrary1;
class Program
{
    static void Main(string[] args)
    {
        var assembly = new AssemblyCatalog(typeof(Program).Assembly);
        using (var container = new CompositionContainer(assembly))
        {
            var co = new ComposableObject(container);
            co.DoWork();
        }

        Console.ReadKey(true);
    }
}

The bits at the beginning are creating a CompositionContainer using the current assembly. MEF allows you to load containers from all sorts of sources however, including entire directores full of Assemblies so you can have an easy add-in system. The ComposableObject is the one defined in my Silverlight Assembly! No interop nastiness, no AppDomain hassles, it just loads the dll as if it were true .NET code!

Next all I have to do is create an instance of the IStateService and export it.

[Export(typeof(IStateService))]
public class ParallelProcessingService : IStateService
{
    private Stream state;

    public Stream State
    {
        get
        {
            if (state == null)
                state = File.Create("state.dat");
            return state;
        }
    }

    public void Dispose()
    {
        if (state != null)
            state.Dispose();
    }
}

Now when I run this application, my Silverlight code will use MEF to load an Exported IStateService instance for me. Running this code will the access the FileSystem directly even though I’m running a Silverlight class library.

So what you should do is to create a Class Library with all of your logic, composed in a similar fashion as the above. Then in your Silverlight Application you simply implement and Export all of the Silverlight specific code as services. You do the same for your unit testing in .net projects and you’ll be able to run the exact same assembly in both locations.

The bonus to this, of course, is that you’ll also be able to swap out logic that you want to actually be different in different locations as well. For example, if you’re creating a business application you could put all of your business logic into a single assembly that could be run on both the client and the server. However, what that logic does and how it does it might be different in both locations. You may need to do a server call to a database to determine if a particular value of your business object is unique. On the client you want to make an asynchronous web request back to the server but on the server you want to make a call directly to the Database. It’s the same object and assembly in both locations so in order to achieve this you need to make the ValidateUnique rule itself composable, then this is possible even though the object is simply applying the rule in the same way.

In fact this technique can be very pervasive and powerful in general. Running on multiple frameworks requires you to be composable, which may also inadvertently force you into some good practices in general.

One other thing to note. I had to set CopyLocal=True for some of my references in the Silverlight Class Library to get it to run correctly in .NET. Since those assemblies aren’t in the GAC by default, it won’t load them unless they tag along with your assembly.

image

I didn’t test this out myself but you wouldn’t want those files appearing in your .xap file for your Silverlight application. I’m pretty sure that it would be smart enough to exclude them but double check.